我希望用户在按下键盘上的任意键后的第一个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;
        }
      }
    }

   }

最佳答案

您可以创建此函数(仅对输入键有用)并在代码中所需的任何位置使用它:

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

关于java - 如何使 “Press any key to continue”在Java代码中工作?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19870467/

10-16 01:23