【问题标题】:Java do-while loop not working [duplicate]Java do-while循环不起作用[重复]
【发布时间】:2018-07-30 14:39:45
【问题描述】:

我正在用 Java 编写一个程序,但我遇到了 do-while 循环的问题。我在下面发布了代码,但为了便于阅读,我删除了大部分代码。运行程序时发生的情况是 do-while 循环中的前 4 行打印到屏幕上,然后我输入使用键盘选择的“选项”,最后一行询问我是否要执行另一个动作打印到屏幕上,然后程序就结束了,不允许我输入“是或否”来指示我是否要执行另一个动作。但是,如果我只删除“value = scan.nextInt();”行和“System.out.println(value);”行,那么当我被问及是否要执行另一个操作时,我可以输入“是或否”。

有人明白为什么 do-while 循环不像我在下面写的那样工作吗?

import java.util.Scanner;

public class Test
{
   public static void main(String[] args)
   {
      String another;

      int value;

      Scanner scan = new Scanner(System.in);

      do
      {
         System.out.println("Enter the numerical value of one of the following options in order to select an option:");
            System.out.println("1. Option 1");
            System.out.println("2. Option 2");
            System.out.println("3. Option 3");

         value = scan.nextInt();
         System.out.println(value);

         System.out.print("Would you like to perform another action (yes/no)?");
         another = scan.nextLine();
      }
      while (another.equalsIgnoreCase("yes"));
   }
}

提前谢谢你。

【问题讨论】:

  • nextInt 不可能消耗 newLine 字符,然后当它读取到另一个变量时,它会读取这个换行符并终止,因为 "\n" 不等于 "yes"跨度>
  • 只要使用scan.next()就可以解决问题了。

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


【解决方案1】:
import java.util.Scanner;

public class Test
{
   public static void main(String[] args)
   {
      String another;

      int value;

      Scanner scan = new Scanner(System.in);

      do
      {
         System.out.println("Enter the numerical value of one of the following options in order to select an option:");
         System.out.println("1. Option 1");
         System.out.println("2. Option 2");
         System.out.println("3. Option 3");

         value = scan.nextInt();
         System.out.println(value);
         scan = new Scanner(System.in);
         System.out.print("Would you like to perform another action (yes/no)?");
         another = scan.nextLine();
         if(another.equalsIgnoreCase("no")){
             break;
         }
      } while (true);
   }
}

试试这个方法

输出

Enter the numerical value of one of the following options in order to select an option:
1. Option 1
2. Option 2
3. Option 3
1
1
Would you like to perform another action (yes/no)?yes
Enter the numerical value of one of the following options in order to select an option:
1. Option 1
2. Option 2
3. Option 3
2
2
Would you like to perform another action (yes/no)?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-15
    • 2020-11-26
    • 2022-12-12
    • 1970-01-01
    • 2015-11-01
    相关资源
    最近更新 更多