Alright, guys, I’m trying to get a basic hang on Java and I figured I would make something a bit more complicated than usual. What I have in this method is an attempt to first check if the first character can be an int, and if it is, I want to see how far that number will go in the input (so if the user inputted 455+60, I’d want to pull out the 455 and stop at the +).
For some reason, if the input is 500t, it will work fine. But if the index ends after the number (say the input is just 500), it has a problem. I am thinking the for loop keeps going for some reason. Can someone tell me where I messed up? I added an if statement to see if I could stop it, but to no avail.
public void init(){
int chars = 0;
/*
* Input fancy intro here.
*/
clearArray();
String uInput = getInput();
rawInput=uInput.toCharArray();
cleanArray(rawInput);
try{Integer.parseInt(Character.toString(rawInput[0]));
boolean isNum = true;
for(int i=0;isNum==true;i++){
if(i != rawInput.length){
try{Integer.parseInt(Character.toString(rawInput[i]));}
catch (NumberFormatException s){
isNum = false;
chars = i;
System.out.println("The number has: "+chars+" characters.");
}
}
}
}
catch (NumberFormatException s){
System.out.println("What is this madness?");
}
}
Here, you avoid asking for
rawInput[rawInput.length]:… but you do keep going for the next iteration.
Is there any reason you can’t just do:
? I would also suggest using
Character.isDigitor a custom check rather than converting each character to a string, then parsing it and catching an exception.Note that
Character.isDigitwill returntruefor non-ASCII digits, which you may not want. You quite possibly just want a simple check of:Also note that a regular expression may well be a better solution for this…
Oh, and if you’ve got an empty string, that will count as a number at the moment…