How do I make my code run in a loop and ask the user “Try again Yes or no?”

橙三吉。 提交于 2019-12-20 07:56:16

问题


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.");

      }

   }
}

So how do I put the "Try again yes or no"? just that.. then if I enter y .. it will ask the user the size of the square again .. if letter n it will exit .. this is for magic square


回答1:


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

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

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



回答2:


Put your code that computes your magic square in a separate method, and have your input reading code in a while loop, that calls that method until the user presses N, for example.




回答3:


Wrap the try/catch statement with a while loop.

while(not true) {
    do foo()
}



回答4:


Check out the Scanner class.



来源:https://stackoverflow.com/questions/7611015/how-do-i-make-my-code-run-in-a-loop-and-ask-the-user-try-again-yes-or-no

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!