【问题标题】:Setting limitation for running a while loop in java [closed]在java中设置运行while循环的限制[关闭]
【发布时间】:2020-10-03 22:32:52
【问题描述】:

这是我班上的一个简单项目。如果用户输入超过 3 次程序应该终止,则用户只能输入 3 次错误输入。我不知道我应该使用什么循环。请提供一些想法。我尝试使用 FOR 循环,但它不起作用

public class Main {

public static void main(String[] args) {

    int numl = readNumber("number1", 1, 10);
    int num2 = readNumber("number2", 11, 20);
    int add = Total(numl + num2);
}

public static int readNumber(String Prompt, int min, int max) {
    int value ;
    Scanner scanner = new Scanner(System.in);
        while (true) {
            System.out.print(Prompt);
            value = scanner.nextInt();
            if ((value >= min && value <= max)) {
                break;
            }
        }
    return value;
}
public static int Total(int sum) {
    System.out.println("SUM = " + sum);
    return sum;
}
}

【问题讨论】:

  • 任何循环都可以。删除图像并将代码作为文本发布。
  • 欢迎来到 Stack Overflow!请访问help centertour 以查看内容和How to Ask。做一些研究,搜索关于 SO 的相关主题;如果您遇到困难,请发布您尝试的minimal reproducible example,注意输入和预期输出,最好在Stacksnippet 中 - 显示代码,而不是代码图片
  • 所以,用户有 3 次更改,每个数字都会出错,或者整个应用程序有 3 次出错的机会??
  • @ΦXocę웃Пepeúpaツ 对于每个号码,他有 3 次机会,或者用户总共有 6 次机会。

标签: java if-statement error-handling while-loop


【解决方案1】:

我建议你使用do-while 循环(这并不意味着你不能使用其他类型的循环来解决它),因为它会使代码易于理解。 do-while 循环保证其主体将至少执行一次。

您还需要一个变量,例如int attempts 跟踪尝试次数。

按如下方式进行:

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        int numl = readNumber("Number1: ", 1, 10);
        int num2 = readNumber("Number2: ", 11, 20);
        int add = Total(numl + num2);
    }

    public static int readNumber(String Prompt, int min, int max) {
        int value;
        int attempts = 0;
        Scanner scanner = new Scanner(System.in);
        do {
            System.out.print(Prompt);
            value = scanner.nextInt();
            if ((value >= min && value <= max)) {
                break;
            }
            attempts++;
        } while (attempts < 3);

        if (attempts == 3) {
            // Reset `value`
            value = 0;
        }

        return value;
    }

    public static int Total(int sum) {
        System.out.println("SUM = " + sum);
        return sum;
    }
}

示例运行:

Number1: 10
Number2: 15
SUM = 25

另一个示例运行:

Number1: 50
Number1: 56
Number1: -1
Number2: 23
Number2: -60
Number2: 50
SUM = 0

下面给出的是使用while 循环而不是do-while 循环的代码:

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        int numl = readNumber("Number1: ", 1, 10);
        int num2 = readNumber("Number2: ", 11, 20);
        int add = Total(numl + num2);
    }

    public static int readNumber(String Prompt, int min, int max) {
        int value;
        int attempts = 0;
        Scanner scanner = new Scanner(System.in);
        while (true) {
            if (attempts == 3) {
                // Reset `value`
                value = 0;
                break;
            }
            System.out.print(Prompt);
            value = scanner.nextInt();
            if ((value >= min && value <= max)) {
                break;
            }
            attempts++;
        }

        return value;
    }

    public static int Total(int sum) {
        System.out.println("SUM = " + sum);
        return sum;
    }
}

【讨论】:

  • 超级编码但是我们可以不使用Do-while循环而只使用While循环吗。
  • @NaVeEdIbRaHiM - 我已经发布了使用while 循环的方法。如有任何疑问/问题,请随时发表评论。
  • 好先生。 Tnx 给你回复
【解决方案2】:

很好地尝试了 2 种不同的变体。问题的主要原因是while(true) 段。您要做的是在该段中放置一个条件,每次进行迭代时都会检查该条件。既然你想检查尝试次数是否小于某个最大值,那么你需要检查一下。

请注意,在我所做的修改中,如果在任何变体中都不满足 while 循环段中的条件,则会引发 IllegalStateException,表明未找到结果。

public class Main {

    public static void main(String[] args) {
        try {
            int numl = readNumber("number1", 1, 10, 3);

            int num2 = readNumber("number2", 11, 20, 3);

            int add = Total(numl + num2);
        } catch (IllegalStateException ise) {
            // tell user they exceeded N attempts in 1 of the 2 numbers

        }
}
public static int readNumber(String Prompt, int min, int max, int availableAttempts) {
    int value;

    int attempts = 0;

    Scanner scanner = new Scanner(System.in);
    while (attempts++ < availableAttempts) {
        System.out.print(Prompt);

        value = scanner.nextInt();

        if ((value >= min && value <= max)) {
            return value;
        }
    }
    throw new IllegalStateException();
}

public static int Total(int sum) {
    System.out.println("SUM = " + sum);

    return sum;
}

【讨论】:

  • 英雄先生,您提供的这段代码效果很好。但是我可以知道 catch (IllegalStateException) 的用法并抛出新的 IllegalStateException。是否应该在 Main 类中定义“catch (IllegalStateException)”?
  • 如果我理解你的问题,上面我的示例中提供了如何使用 try-catch 的用法。至于为什么,向方法的调用者指示发生了一些意外状态更有意义,例如没有在某些范围内输入数字,因此抛出异常而不是像 Strings#indexOf 函数那样返回一些任意数字例如返回 -1。
猜你喜欢
  • 1970-01-01
  • 2014-03-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-27
  • 2018-08-14
  • 1970-01-01
相关资源
最近更新 更多