I have the following code:
Scanner inputSide = new Scanner(System.in);
double side[] = new double[3];
int i = 0;
do{
try{
System.out.println("Enter three side lengths for a triangle (each followed by pressing enter):");
side[i] = inputSide.nextDouble();
i++;
}
catch(Exception wrongType){
System.err.println(wrongType);
System.out.println("Please enter a number. Start again!!");
i=0;
}
}
while(i<3);
It works fine and does what it’s meant to if I don’t enter a wrong data type but if I enter something other than a double then it loops over and over, printing everything in both try and catch blocks instead of waiting for me to enter another double.
Any help as to why it’s doing this – as I can’t seem to understand why – would be appreciated.
Thank you 🙂
The problem is that, you have used
input.nextDoublemethod, which reads only the next token in the input, thus skipping thenewlineat the end. See Scanner.nextDoubleNow, if you enter wrong value first time, then it will consider the
newlineas the next input. Which will also be invalid.You can add an empty
input.nextLinein the catch block.Now, your
nextLine()will read thelinefeedleft over, and linefeed will not be taken as input to yournextDoublenext time. In which case, it will fail, even before you giving any input.