How do I get “Press any key to continue” to work in my Java code?

I want the user to enter information again in the first while loop after pressing any key on the keyboard. How do I achieve that? Am I doing something wrong with the while loops. SHould I just have one while loop?

 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());
        }
     }

Leave a Comment