18

キーボードの任意のキーを押した後、最初の while ループでユーザーに情報を再度入力してもらいます。どうすればそれを達成できますか?while ループに何か問題がありますか。while ループを 1 つだけ使用する必要がありますか?

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

   }
4

4 に答える 4

24

この関数を作成して ( Enter キーにのみ有効)、コード内の好きな場所で使用できます。

 private void pressAnyKeyToContinue()
 { 
        System.out.println("Press Enter key to continue...");
        try
        {
            System.in.read();
        }  
        catch(Exception e)
        {}  
 }
于 2014-08-02T12:29:11.880 に答える
3

1) 見while(run1 = true)て、 while(run2 = true)

= は Java の代入演算子です。== 演算子を使用してプリミティブを比較する

2)あなたはこのようにすることができます

while(in.hasNext()){

}
于 2013-11-08T23:48:34.753 に答える