Alison Z Alison Z - 1 year ago 53
Java Question

Failed to parse a String to int

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


public class TheWindow {

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

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

Answer Source

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.