Alison Z
Alison Z

Reputation: 95

Failed to parse a String to int

I don't know what's wrong with parsing the String to an int part in my code. Before the parsing, everything looks correct.

import java.io.IOException;

public class TheWindow {

    public static void main(String[] args) throws IOException{

        String s = "13.16";
        double d = Double.parseDouble(s);
        System.out.println(d);
        char[] ch = s.toCharArray();
        char[] ch2 = new char[s.length()];
        for(int i = 0; i < ch.length; i++){
            if(ch[i] == '.'){
                break;
            }else{
                ch2[i] = ch[i];
            }
        }
        String s2 = new String(ch2);
        System.out.println(s2);
        try{
            s2.trim();
            int newI = Integer.parseInt(s2);
            System.out.println(newI);
        }catch(Exception e){
            System.out.println("Failed");
        }
    }
}

Upvotes: 0

Views: 573

Answers (6)

Victor Havin
Victor Havin

Reputation: 1183

You have uninitialized characters in your ch2 array. You can set them to space before trimming or use a different string constructor. For example:

        public static void main(String[] args) {

        String s = "13.16";
        double d = Double.parseDouble(s);
        System.out.println(d);
        char[] ch = s.toCharArray();
        char[] ch2 = new char[s.length()];
        int i = 0;
        for(i = 0; i < ch.length; i++){
            if(ch[i] == '.'){
                break;
            }else{
                ch2[i] = ch[i];
            }
        }
        String s2 = new String(ch2, 0, i);
        System.out.println(s2);
        try{
            s2.trim();
            int newI = Integer.parseInt(s2);
            System.out.println(newI);
        }catch(Exception e){
            System.out.println("Failed");
        }
    }

}

Upvotes: 0

Kent Bull
Kent Bull

Reputation: 1152

The problem with your code is that you are breaking out of the for loop when the '.' character is reached.

Since you created ch2 with a length of 5 then this means the last three spaces are null. When you put that in a string with String s2 = new String(ch2) then then three special characters are added at the end of the string, one for each empty space in the ch2 character array.

To fix this then set the length of the ch2 array to be two, or if you want to dynamically determine the length, do the index of the '' in theString swiths.indexOf('.')and then set the length of the array to one minus the index of ''.

This should fix your problem as stated in your question.

Upvotes: 0

OneCricketeer
OneCricketeer

Reputation: 191710

From what I understand, you want to truncate the decimal. If so, then you can just find the decimal place and substring the string, then parse it.

Note: You might want to add back in some try-catches for strings that still cannot be parsed.

private static int tryParseInt(String str) {
    int decimalIndex = str.indexOf(".");

    if (decimalIndex != -1) {
        return Integer.parseInt(str.substring(0, decimalIndex));
    } else {
        return Integer.parseInt(str);
    }
}

public static void main(String[] args) {
    System.out.println(tryParseInt("13.16")); // 13
}

Upvotes: 0

Timothy Deng
Timothy Deng

Reputation: 494

Java objects are immutable, meaning they can't be changed, and Strings are Objects in Java.

Your line s2.trim() will return the trimmed version, but s2 will not be directly modified. However, you aren't storing it anywhere, so when you parse it on the next line, it will be with the untrimmed s2.

What you want is s2 = s2.trim(), which will store the trimmed version back in.

Upvotes: 0

Rishi
Rishi

Reputation: 1183

s2 = s2.trim(); 

change this part of code in the try block.

You are trimming the string but not assigning it to the variable that refers it due to which the spaces are still left out and parsing such string is throwing an exception.

Upvotes: 0

Matthew Diana
Matthew Diana

Reputation: 1106

You are not storing the returned String from trim() anywhere. You could either do:

s2 = s2.trim();
int newI = Integer.parseInt(s2);

or

int newI = Integer.parseInt(s2.trim());

Upvotes: 3

Related Questions