我必须检查用户的输入是否为int且在1-100的范围内。我知道我必须使用input.hasNextInt()函数,但我似乎无法正确地将它放在代码中。我是编程新手,如果有人能给我任何其他的建议或建议,我将不胜感激。
import java.util.Scanner;
public class PartA {
public static void main (String[] args){
int numberToGuess = (int)(Math.random() * 100) + 1;
int numberOfTries = 0;
Scanner input = new Scanner(System.in);
System.out.print("I'm thinking of a number. Guess a value (1-100): ");
int guessNumber = input.nextInt();
boolean win = false;
while (win == false){
numberOfTries++;
if (guessNumber < numberToGuess)
{
System.out.print("Too Low. Guess again: ");
guessNumber = input.nextInt();
}
else if (guessNumber > numberToGuess)
{
System.out.print("Too High. Guess again: ");
guessNumber = input.nextInt();
}
else
{
System.out.println("Correct! You got it in " + numberOfTries + " tries.");
win = true;
}
}
}
答案 0 :(得分:0)
以下更改有助于正确的操作:
public static void main(String[] args) {
Scanner input = null;
try {
int numberToGuess = (int) (Math.random() * 100) + 1;
int numberOfTries = 0;
System.out
.print("I'm thinking of a number. Guess a value (1-100): ");
input = new Scanner(System.in);
boolean win = false;
do {
while (!input.hasNextInt()) { //Handle non-integer entry
input.next();
System.out.println("Expecting a number. Try again.");
}
int guessNumber = input.nextInt();
numberOfTries++;
if (guessNumber < numberToGuess) {
System.out.print("Too Low. Guess again: ");
// guessNumber = input.nextInt(); - Reading in a single
// place
} else if (guessNumber > numberToGuess) {
System.out.print("Too High. Guess again: ");
// guessNumber = input.nextInt(); - Reading in a single
// place, above
} else {
System.out.println("Correct! You got it in "
+ numberOfTries + " tries.");
win = true;
}
} while (!win);
} finally {
input.close(); // Closing the scanner stream
}
}