java - Failed to parse a String to int -
i don't know what's wrong parsing string int part in code. before parsing, 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 = 0; < 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"); } } }
the problem code breaking out of loop when '.' character reached.
since created ch2
length of 5 means last 3 spaces null. when put in string string s2 = new string(ch2)
then 3 special characters added @ end of string, 1 each empty space in ch2
character array.
to fix set length of ch2
array two, or if want dynamically determine length, index of '' in the
string swith
s.indexof('.')and set length of array 1 minus index of '
'.
this should fix problem stated in question.
Comments
Post a Comment