【问题标题】:'while' infinite loop using scanner input and pos/neg numbers'while' 无限循环使用扫描仪输入和 pos/neg 数字
【发布时间】:2020-02-12 03:22:05
【问题描述】:

我似乎无法理解如何使用 while 循环来确定一个数字是否为正数。 While (I > 0),如果我输入任何正数,结果总是大于 0,这意味着存在无限循环。

int i = 0;

System.out.println("#1\n Input Validation\n Positive values only"); // #1 Input Validation
System.out.print(" Please enter a value: ");

Scanner scan = new Scanner(System.in);
i = scan.nextInt();

while (i > 0)
{
    System.out.println("The value is: " +i);
} 

System.out.println("Sorry. Only positive values.");

另外,当我输入一个负数时,它不会返回扫描仪输入一个正数。

【问题讨论】:

  • 将 Scanner 放入 while 循环中,

标签: java loops while-loop integer java.util.scanner


【解决方案1】:

你可以采用这种方法:

    int i = 0;

    System.out.println("#1\n Input Validation\n Positive values only"); // #1 Input Validation

    Scanner scan = new Scanner(System.in);

    while (i >= 0) {
        System.out.print(" Please enter a value: ");
        i = scan.nextInt();
        if (i > 0) {
            System.out.println("The value is: " + i);
        } else {
            break;
        }
    }

    System.out.println("Sorry. Only positive values.");

【讨论】:

    【解决方案2】:

    我相信这就是您想要实现的目标。

        int i = 0; // int is 0
    
        while (i <= 0) {
            // int is 0 or a negative number
            System.out.println("#1\n Input Validation\n Positive values only");
            System.out.print(" Please enter a value: ");
            Scanner scan = new Scanner(System.in);
            i = scan.nextInt();
    
            if (i > 0) {
                System.out.println("The value is: " + i);
            } else {
                System.out.println("Sorry. Only positive values.");
            }
            // if number is positive then continue to termination. If negative then repeat loop
        }
    

    密切注意放置 while 循环的位置,因为初始放置肯定会导致无限循环

    while (i > 0)
    {
        System.out.println("The value is: " +i);
        // number is positive - repeat loop containing only this line of code to infinity
    }
    // number is either 0 or negative so continue to termination
    

    【讨论】:

      猜你喜欢
      • 2013-11-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-19
      • 1970-01-01
      • 2011-06-16
      • 2010-12-20
      相关资源
      最近更新 更多