有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

我在做一个猜谜游戏,所有的代码都很好,除了我想让他们猜一个数字,我似乎不知道如何做,如果用户输入一个字母“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) 个答案

  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. # 2 楼答案

    这样做:

    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
    
  3. # 3 楼答案

    使用试捕

    比如说 试一试{ int a=sc.nextInt(); }捕获(例外e){ 系统出来println(“非整数”); }