Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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

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

   }
like image 675
user2840682 Avatar asked Nov 08 '13 23:11

user2840682


People also ask

Do you want to continue code in Java?

println("Do you want to continue y or n"); String c = input. nextLine(); if(c. equalsIgnoreCase("n")){ break; }//else continue to loop on any string ;-) } answer.


1 Answers

You can create this function (good only for enter key) and use it where ever you want in your code:

 private void pressAnyKeyToContinue()
 { 
        System.out.println("Press Enter key to continue...");
        try
        {
            System.in.read();
        }  
        catch(Exception e)
        {}  
 }
like image 72
E235 Avatar answered Sep 23 '22 14:09

E235