如果用户输入一个字母而不是一个数字告诉他们这不是一个数字

时间:2015-09-25 16:38:14

标签: java if-statement numbers

我正在制作一个猜谜游戏,所有的代码都工作得很好,除了我希望他们在一个数字之间进行猜测,我似乎无法弄清楚如何制作它以便如果用户输入一个字母像“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");
    }
}
}

3 个答案:

答案 0 :(得分:1)

使用try catch

例如,

    尝试{     int a = sc.nextInt();     } catch(例外e){     System.out.println(&#34;不是整数&#34;);     }

答案 1 :(得分:1)

您可以使用nextLine()代替nextInt()并检查即将出现的字符串matches()正则表达式[1-9] [0-9] *然后解析该行与Integer.valueOf(str)

像:

String str=input.nextLine();
int i=0;
if(str.matches("[1-9][0-9]*"){
    i=Integer.valueOf(str);
} else {
    System.out.println("This is not allowed!");
}

我希望它有所帮助。

答案 2 :(得分:1)

做这样的事情:

Scanner scan = new Scanner(System.in);
while(!scan.hasNextInt()) { //repeat until a number is entered.
    scan.next();
    System.out.println("Enter number"); //Tell it's not a number.
}
int input = scan.nextInt(); //Get your number here