Код:
if (stdin.hasNextInt())
{
AmtMiles = stdin.nextInt();
}
else
{
String Miles = stdin.next();
System.out.println(Miles + " not valid. I will use 100 for the number of miles.");
}
Thank you.
That piece of code works.
I tried something similar and got an error and I gave up on that route.
So the lesson is: I should have simply placed the
integer check inside of the body of the
if statement. If that fails, the
else statement checks and moves onto the next line. Am I correct?
You have enlightened me here:
Цитата:
And why do you have keyboard and stdin both scanning System.in? That leads to nasty bugs.
I used different scan methods because of errors and I thought it a good idea to change one.
Could you give me an outline as to why it leads to bugs?
I'll do some self-research afterwards.
-- Пт мар 08, 2013 05:55:25 --The input is read before hasNextInt check is done.
Delete lines 21-23 and change Miles = keyboard.next(); to AmtMiles = keyboard.nextInt();
Код:
Scanner stdin = new Scanner(System.in);
Scanner keyboard = new Scanner(System.in);
System.out.println("Where do you travel to?: ");
String Destination = stdin.next();
System.out.println(Destination + " is how many miles away?");
if (keyboard.hasNextInt())
{
AmtMiles = keyboard.nextInt();
System.out.printf("\n%s is %d miles away. You will need %.2f gallons, or %.4f liters of fuel.", Destination, AmtMiles, (AmtMiles/23.0),(3.78541178*AmtMiles/23.0));
}
else
{
String Miles = stdin.next();
System.out.println(Miles + "not valid. I will use 100 for the number of miles.");
}
}
This works fine when the expected inputs are entered. Otherwise, it accepts outputs nothing.