Java do-while循环不起作用

时间:2018-07-30 14:39:45

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

我正在用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"));
   }
}

谢谢。

1 个答案:

答案 0 :(得分:0)

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)?