我正在做一个猜谜游戏,所有代码都可以正常工作,除了我希望他们在其中猜一个数字之外,我似乎无法弄清楚怎么做,以便用户输入“ d”这样的字母”,而不是“ 15”之类的数字,它会告诉他们他们不能这样做。
码:

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

public class GuessingGame {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        Random rand = new Random();

        while (true) {
            System.out.print("Pick a number: ");
            int number = input.nextInt();

            if (number != int) {
                System.out.println("That's not a number");
            } else if (number == int) {
            int random = rand.nextInt(number);
            break;
        }
    }

        System.out.println("You have 5 attempts to guess the number or else you fail. Goodluck!");
        System.out.println("");
        System.out.println("Type 'begin' to Begin!");
        System.out.print("");
        String start = input.next();

        if (start.equals("begin")) {
            System.out.print('\f');
        for(int i=1; i<6; i++) {
            System.out.print("Enter a number between 1-" + number + ": ");
            int number = input.nextInt();

            if (number > random) {
                System.out.println("Too Big");
                System.out.println("");
            } else if (number < random) {
                System.out.println("Too Small");
                System.out.println("");
            } else if (number == random) {
                System.out.print('\f');
                System.out.println("Correct!");
                break;
            }

            if (i == 5) {
                System.out.print('\f');
                System.out.println("You have failed");
                System.out.println("Number Was: " + random);
                }
            }
        } else if (start != "begin") {
            System.out.print('\f');
            System.out.println("Incorrect Command");
            System.out.println("Please Exit Console And Retry");
    }
}
}

最佳答案

使用try catch

例如
    尝试{
    int a = sc.nextInt();
    } catch(Exception e){
    System.out.println(“非整数”);
    }

10-07 15:57
查看更多