Java 将用户输入与整数进行比较
我还在学习Java。我做了一种猜谜游戏。看起来是这样的:Java 将用户输入与整数进行比较,java,integer,Java,Integer,我还在学习Java。我做了一种猜谜游戏。看起来是这样的: import java.util.Scanner; import java.util.Random; public class guessing_game { static Scanner input = new Scanner(System.in); static Random generator = new Random(); public static void main(String[] args) {
import java.util.Scanner;
import java.util.Random;
public class guessing_game {
static Scanner input = new Scanner(System.in);
static Random generator = new Random();
public static void main(String[] args) {
int number;
number = generator.nextInt(20);
System.out.println("Guess the number!");
game(number);
}
public static void game(int number) {
int inputStorage;
inputStorage = input.nextInt();
if (inputStorage == number) {
System.out.println("You've guessed the right number!");
}
else if (inputStorage != number) {
System.out.println("Wrong number, try again!");
game(number);
}
}
}
现在我有一个问题。我和妹妹玩了这个“游戏”。我妹妹正在用键盘打字。她在按enter键之前不小心按了+键,我出现了一些错误。我的问题是:如何让我的应用程序打印一行内容,表明您只能输入数字,然后再次重新启动游戏存根?一种方法是将input.nextInt()封装在try-catch语句中,并捕获input.nextInt(),inputmaschException引发的异常。关于try-catch语句的一个很好的教程是,如果您不确定我在说什么
try {
inputStorage = input.nextInt();
} catch (InputMismatchException e){
System.out.println("invalid type");
}
另一种方法是:
if(input.hasNextInt()){
inputStorage = input.nextInt();
}else{
System.out.println("invalid type");
}
继续游戏时也会出现错误。如果正确猜到数字,请尝试使用带中断的while循环:
int inputStorage;
boolean notGuessed = true;
while(notGuessed)
{
if(input.hasNextInt()){
inputStorage = input.nextInt();
} else{
System.out.println("invalid type");
}
if (inputStorage == number) {
System.out.println("You've guessed the right number!");
notGuessed = false;
}
else if (inputStorage != number) {
System.out.println("Wrong number, try again!");
}
}
您可以使用
try/catch
:
boolean b = true;
while (b) {
try {
inputStorage = input.nextInt();
b= false;
} catch (InputMismatchException e) {
System.out.println("Invalid input. Please enter again!");
}
}
因为您得到的错误是一个例外:
输入不匹配例外
可以使用java中的异常处理机制显式处理异常
阅读
阅读
了解它的实际工作原理
以上建议的答案仅用于异常处理。这很容易。你可以用各种方式来完成它 试试这个
public static int checkInt(String strNumber) {
int Number;
try {
Number = Integer.parseInt(strNumber);
} catch (NumberFormatException ex) {
Number = -1;
}
return Number;
}
或者更简单:
public static int checkInt(String strNumber) {
Number = Integer.parseInt(strNumber, -1);
return Number;
}
第二个更简单,因为您省略了try-catch块,而在这种情况下,try-catch块并没有正确使用。阅读Integer类的函数。我是Java的真正初学者,是否可以将未猜测的布尔值更改为猜测并默认设置为false?我现在不在我的电脑上,所以我无法测试它…是的,这是可能的,但您必须在while条件中添加一个逻辑or:while(!gustized)。它不起作用。当我输入一个字母时,会出现“无效类型”文本,并且不会停止打印。它不停地前进……在正确猜出数字之前,它不应该停止。如果你想要一个不同的条件,那么改变循环结构。我让它只打印一次无效的类型文本,但我不明白为什么它现在能工作。