Java异常处理循环错误

标签 java

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

当我在尝试 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/

相关文章:

带有双数组的 Java System.out.format

java - Spring Boot 显示对索引的 http 请求,但不显示任何其他映射

java - 绑定(bind)按键移动图片

java - 在没有事件总线的情况下触发事件时自动从 observable 获取项目

java - 使用 JDBC 和持久数据存储添加 Apache Ignite 同步数据

java - GLFW 的线程设置

java - 当我使用 hibernate 类在 MySQL 中选择一行时,它会自动进行更新

java - 如何打印字符串中的每个字符?

java - 如何在同一类中的静态方法中抛出异常

java - 是否有特定的机制可以在 Quartz 调度程序 API 中运行的作业中进行日志记录?