gpt4 book ai didi

Java异常处理循环错误

转载 作者:行者123 更新时间:2023-12-01 21:49:19 25 4
gpt4 key购买 nike

我想出了一切办法来寻求帮助

当我在尝试 1/4 处输入字母时,它工作正常并继续,但是一旦我在尝试 2/4 处输入字母,它只会打印消息并且程序停止。还有关于#2的任何提示,我只能想到 if(guess>=4 &&guess<=16) else 语句(不确定这是否正确)

当我执行代码时 -

Guess a number between 1 and 16.

Attempt 1 of 4: 8

You guessed 8

Too Low!

Attempt 2 of 4: a

Please enter an integer between 4-16

之后无法输入任何内容

问题:如果用户输入 a,我必须创建异常处理程序

1) 非数字输入

2)输入超出范围

3)必须保留当前猜测金额

import java.util.InputMismatchException;
import java.util.Random;
import java.util.Scanner;

public class GuessingGame {

static final int limit = 4;
static final int maxInteger = 16;

public static void main(String[] args) {

Random rand = new Random();
int target = rand.nextInt(maxInteger) + 1;
int x = 1;

do{
try{
Scanner input = new Scanner(System.in);
System.out.printf("Guess a number between 1 and %d.\n", maxInteger);


int attempts = 1;
while (attempts <= limit) {
System.out.printf("Attempt %d of %d: ", attempts, limit);


int guess = input.nextInt();
System.out.printf("You guessed %d\n", guess);

if(guess > target) {
System.out.printf("Too High! \n");

}
else if(guess == target){

System.out.printf("The answer is %d, You win!", guess);
attempts = 20;

}
else{
System.out.printf("Too Low! \n");

}

attempts+=1;
x = 2;
}
if(attempts==5){
System.out.println("You lose!");
}
}
catch(InputMismatchException e){
System.out.printf("Please enter an integer between 4-16");
continue;


}
}while(x == 1);
}
}

最佳答案

您正在检查while(x == 1);在外循环和内循环中,您增加了 x 的值通过这样做x = 2; 。这将打破条件,你将从外部 while 中出来。循环。

您应该为外部 while 设置有效条件如果您想继续,请循环。尝试类似 while(x < 5);

您的代码应如下所示:

do {
try {
...
/* Inner While */
while() {}
...
} catch () {
/* Exception Handling */
...
}
} while(x < 5); /* Decide a valid condition */

关于Java异常处理循环错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35443006/

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