如何让“按任意键继续”在我的 Java 代码中工作?

新手上路,请多包涵

我希望用户在按下键盘上的任意键后在第一个 while 循环中再次输入信息。我该如何实现?我在 while 循环中做错了什么吗?我应该只有一个 while 循环吗?

  import java.util.Scanner;

 public class TestMagicSquare
 {
  public static void main(String[] args)
 {
    boolean run1 =  true;
    boolean run2 = true;

    Square magic = new Square();

    Scanner in = new Scanner(System.in);

    while(run1 = true)
    {
        System.out.print("Enter an integer(x to exit): ");
        if(!in.hasNextInt())
        {
            if(in.next().equals("x"))
            {
                break;
            }

            else
            {
                System.out.println("*** Invalid data entry ***");
            }
        }
        else
        {
            magic.add(in.nextInt());
        }
     }

    while(run2 = true)
    {
        System.out.println();
        if(!magic.isSquare())
        {
            System.out.println("Step 1. Numbers do not make a square");
            break;
        }
        else
        {
            System.out.println("Step 1. Numbers make a square");
        }

        System.out.println();
        if(!magic.isUnique())
        {
            System.out.println("Step 2. Numbers are not unique");
            break;
        }
        else
        {
            System.out.println("Step 2. Numbers are unique");
        }

        System.out.println();
        magic.create2DArray();
        if(!magic.isMagic())
        {
            System.out.println("Step 3. But it is NOT a magic square!");
            break;
        }
        else
        {
            System.out.println("Step 3. Yes, it is a MAGIC SQUARE!");
        }

        System.out.println();
        System.out.print("Press any key to continue...");// Here I want the simulation
        in.next();
        if(in.next().equals("x"))
        {
            break;
        }
        else
        {
            run1 = true;
        }
      }
    }

   }

原文由 user2840682 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.7k
1 个回答

您可以创建此功能( 仅适用于回车键)并在代码中的任何地方使用它:

  private void pressEnterToContinue()
 {
        System.out.println("Press Enter key to continue...");
        try
        {
            System.in.read();
        }
        catch(Exception e)
        {}
 }

如果您使用扫描仪:

  private void pressEnterToContinue()
 {
        System.out.println("Press Enter key to continue...");
        try
        {
            System.in.read();
            scanner.nextLine();
        }
        catch(Exception e)
        {}
 }

原文由 E235 发布,翻译遵循 CC BY-SA 4.0 许可协议

推荐问题