如何使我的代码循环运行并询问用户“再试一次是或否?”

时间:2011-09-30 13:23:21

标签: java magic-square

import java.io.*;
public class Magic{

   static final int maxsize = 50;

    public static void main (String [] args) throws IOException{

      int i, j, k, l, n, key;
      boolean n_ok;
      String line;
      int [] [] square = new int [maxsize] [maxsize];

      BufferedReader KeybIn = new BufferedReader(new InputStreamReader(System.in));

      try{


         System.out.print("Size of square? ");
         line  = KeybIn.readLine();
         n = Integer.parseInt(line);

         n_ok = (1<=n) & (n<=maxsize+1) & (n%2==1);


         if ( n_ok ){


            for (i=0;i<n;i++)
               for (j=0;j<n;j++) square[i][j] = 0;
            square[0][(int)(n-1)/2] = 1;

            key = 2;
            i = 0;
            j = (int)(n-1)/2;
            while ( key <= n*n ){

               k = i - 1;

               if ( k < 0 ) k = k + n;
               l = j - 1;

               if ( l < 0 ) l = l + n;

               if ( square[k][l] != 0 ) i = (i+1) % n;

               else { i = k; j = l; }
               square[i][j] = key;
               key = key + 1;
            }


            System.out.println("Magic square of size " + n);

            for (i=0;i<n;i++)

            {

               for (j=0;j<n;j++)
                  System.out.print("\t"+square[i][j]);
               System.out.println();
            }
         }      
      }catch (NumberFormatException e){

         System.out.println("Error in number, try again.");

      }

   }
}

那我怎么把“再试一次是或否”?只是..那么如果我输入y ..它将再次询问用户方形的大小..如果字母n它将退出..这是为魔方

4 个答案:

答案 0 :(得分:3)

String tryAgain = "y";
do
{
   // you code

   System.out.println("Try again? enter \"y/n\".");
   tryAgain = System.in.readLine();

}
while(!tryAgain.equals("n"));

答案 1 :(得分:0)

将用于计算魔方的代码放在一个单独的方法中,并在while循环中输入读取代码,然后调用该方法,直到用户按下N为止。

答案 2 :(得分:0)

使用while循环包装try / catch语句。

while(not true) {
    do foo()
}

答案 3 :(得分:-1)

查看Scanner课程。