gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 08:08:58 26 4
gpt4 key购买 nike

我正在做一个猜谜游戏,除了我想让他们猜一个数字之外,所有代码都工作正常,我似乎无法弄清楚如何做到这一点,以便如果用户输入一个字母像“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 (异常e){ System.out.println("不是整数");

关于java - 如果用户输入的是字母而不是数字,则告诉他们这不是数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32786848/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com