java IF NOT语句

G.M*_*G.M 2 java

import java.util.Random;
import java.util.Scanner;

public class Game {
    public static void main(String[] args) {

        System.out.println("Guess a number betwwen 1 and 1000");

        Random rand = new Random(); 
        int secretNumber = rand.nextInt (1000);


        Scanner keyboard = new Scanner(System.in);
        int guess;

        do {
        guess = keyboard.nextInt();

        if (guess == secretNumber)
            System.out.println("You WON!!! Congratulations!");
        else if (guess < secretNumber)
             System.out.println("Nope, to low");
        else if (guess > secretNumber)
            System.out.println("Sorry, to high");


        } while (guess != secretNumber);


    }
}
Run Code Online (Sandbox Code Playgroud)

我怎样才能在这段代码中添加一条语句,如果不是NUMERIC INPUT System.out.println("输入无效,请仅使用类型编号!")

das*_*ght 6

在调用之前,您应该使用Scanner's hasNextInt()方法来确定输入是否为数字nextInt:

do {
    while (!keyboard.hasNextInt()) {
        System.out.println("Please enter only numbers.");
        keyboard.next(); // Skip the wrong token
    }
    // Now that the input is valid, read the value:
    guess = keyboard.nextInt();
    // Put the rest of your logic here
    ...
} while (guess != secretNumber);
Run Code Online (Sandbox Code Playgroud)