【问题标题】:Java: While Loop still running even when the condition is falseJava:即使条件为假,While Loop 仍在运行
【发布时间】:2017-07-21 16:22:39
【问题描述】:

我在编码和一般的 java 方面相当新,但我希望我能弄清楚这一点。我有一个 do while 循环,在其中,如果在扫描仪中输入了不正确的值,我有一个 while 语句。但是,当我运行代码时,它总是运行一次 while 命令,无论它是不正确还是正确,然后才能正确运行代码。

import java.util.Scanner;
public class Practice {
public static void main (String [] args) {
int x = 0;
int i = 0;
int n = 0;
String S1 = "";

Scanner user = new Scanner(System.in);


do
{
    System.out.println("Enter an integer between 1 and 15: ");
    x = user.nextInt();



        while ( x < 1 || x > 15);
        {
            System.out.println("Incorrect integer. Must be between 1 and 15. Try again: ");
            x = user.nextInt();
        }

    n = 1;  


}
while (n != 1);


for (i = 1; i <= x; i++)
{
    S1 = S1 + "X";
}

for (n = 1; n <= x; n++)
{
    System.out.println(S1);
}


    }


}

非常感谢您。

【问题讨论】:

  • 删除;从while语句的结尾
  • @Satya 仅从第一个开始。第二个以do/while 结尾,分号是正确的。
  • @EJP,你说得对,先生 :) 。为错误道歉。

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


【解决方案1】:

从你的 while 循环中删除多余的 ;

像这样:

  while ( x < 1 || x > 15){
            System.out.println("Incorrect integer. Must be between 1 and 15. Try again: ");
            x = user.nextInt();
}

【讨论】:

  • 仅从第一个开始。第二个以do/while 结尾,分号是正确的。
  • @turnipdabeets 非常感谢,我真的很感激。我在每行末尾添加分号时遇到问题。这非常有效!
  • @GavinWebb 没问题,很高兴我能帮上忙!
  • 不要忘记在应用程序末尾使用user.close(); 来关闭扫描仪的键盘输入。
  • 您使用了标有 JavaScript/HTML/CSS sn-p 的图标。 Java 不是 JavaScript、HTML 或 CSS,所以你不应该使用那个图标。
【解决方案2】:

while ( x 15); 分号将终止逻辑,控制将始终传递到下一行。编码时要小心:D

【讨论】:

    【解决方案3】:
    1. 同时删除多余的分号。
    2. 同时关闭扫描仪对象(用户)。

    检查更新的代码。

    public class Practice {
        public static void main(String[] args) {
            int x = 0;
            int i = 0;
            int n = 0;
            String S1 = "";
    
            Scanner user = new Scanner(System.in);
            do {
                System.out.println("Enter an integer between 1 and 15: ");
                x = user.nextInt();
    
                while (x < 1 || x > 15)
                {
                    System.out.println("Incorrect integer. Must be between 1 and 15. Try again: ");
                    x = user.nextInt();
                }
    
                n = 1;
    
            } while (n != 1);
    
            for (i = 1; i <= x; i++) {
                S1 = S1 + "X";
            }
    
            for (n = 1; n <= x; n++) {
                System.out.println(S1);
            }
    
            user.close();
    
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-07
      • 1970-01-01
      • 1970-01-01
      • 2016-05-16
      • 1970-01-01
      相关资源
      最近更新 更多