如何使我的代码循环运行并询问用户“重试是或否?”
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 它将退出..这是魔方
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
例如,将计算幻方的代码放在一个单独的方法中,并将输入读取代码放在 while 循环中,该循环调用该方法直到用户按 N。
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 循环包装 try/catch 语句。
Wrap the try/catch statement with a while loop.
查看 Scanner 类。
Check out the Scanner class.