我想让java给我一个随机数,用户会试图猜测它,如果用户试图输入无效的数据类型,它会说:“无效输入。整数。再试一次”,然后继续代码,但是代码在显示消息后没有推入,即使它有while循环。
我的全部杂务:
import java.util.*;
public class tine {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Random ranNum = new Random();
boolean Win = false;
int nAttempt = 0;
int number = (int)(Math.random()*50 );
int userInput;
System.out.println("Guess a number from 1-50!");
while (Win == false) {
nAttempt++;
try {
userInput = sc.nextInt();
if (userInput < number && userInput >= 1) {
System.out.println("too low.");
}
else if (userInput > number && userInput <= 50){
System.out.println("too high");
}
else if (userInput == number) {
System.out.println("you got it right in " +nAttempt +" attemp(s)");
Win = true;
}
else {
throw new InvalidInputException();
}
}
catch (InputMismatchException im) {
System.out.println("Invalid Input. Integer only. Try Again");
userInput = sc.nextInt();
nAttempt--;
}
catch (InvalidInputException iie) {
System.out.println("Number is out of range. Try Again.");
userInput = sc.nextInt();
nAttempt--;
}
}
} }
class InvalidInputException extends Exception {
InvalidInputException(){
super();
} }
发布于 2022-04-08 14:23:23
扫描程序使用分隔符模式将其输入分解为标记,默认情况下该模式与空白匹配。
而nextInt()则这样做:
将输入的下一个令牌扫描为int。
因此,包含空白的输入将被视为多个输入,这些输入可能不像预期的那样工作。
为了解决这个问题,我建议使用Scanner.nextLine()扫描整行,它“返回当前行的其余部分,不包括末尾的任何行分隔符”;然后使用Integer.parseInt(String)将该行解析为整数,这会在非法模式上抛出运行时异常NumberFormatException,所以最好在catch语句中包含这一点:
try
{
String ln = sc.nextLine();
userInput = Integer.parseInt(ln);
...
}
catch (InputMismatchException | NumberFormatException im)
{...}
catch (InvalidInputException iie)
{...}另外,我没有看到在catch块中读取userInput的意义,因为它将在try块的第一行中再次更新,因为while循环的另一个循环开始了。因此,我建议删除它们:
catch (InputMismatchException im)
{
System.out.println("Invalid Input. Integer only. Try Again");
// userInput = sc.nextInt();
nAttempt--;
}
catch (InvalidInputException iie)
{
System.out.println("Number is out of range. Try Again.");
// userInput = sc.nextInt();
nAttempt--;
}https://stackoverflow.com/questions/71797745
复制相似问题