java 如何让我的代码循环运行并询问用户“再试一次是还是否?”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7611015/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I make my code run in a loop and ask the user "Try again Yes or no?"
提问by Jeffram Catapang
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
那么我该如何放置“再试一次是或否”呢?就是这样..然后如果我输入y..它会再次询问用户正方形的大小..如果字母n它会退出..这是魔术方块
回答by Bala R
String tryAgain = "y";
do
{
// you code
System.out.println("Try again? enter \"y/n\".");
tryAgain = System.in.readLine();
}
while(!tryAgain.equals("n"));
回答by JRL
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.
例如,将计算幻方的代码放在一个单独的方法中,并将输入读取代码放在一个 while 循环中,该循环调用该方法直到用户按下 N。
回答by FloppyDisk
Wrap the try/catch statement with a while loop.
用 while 循环包裹 try/catch 语句。
while(not true) {
do foo()
}