我正在尝试循环询问坐标并从扫描仪获取输入。我想请求输入,直到坐标有效。然而,我对java确实很陌生,循环让我对这项任务感到困惑。 首先,我应该打印一个控制台输出,要求玩家输入一对棋盘坐标。
如果输入是有效坐标,我将以字符串数组形式返回坐标。
如果输入的坐标无效,我应该打印一条错误消息,然后再次询问,直到获得有效的坐标。
public static String[] positionQuery(int dim, Scanner test_in) {
Scanner stdin = new Scanner(System.in);
System.out.println("Provide origin and destination coordinates.");
System.out.println("Enter two positions between A1-H8:");
String s1 = stdin.nextLine();
String[] coordinates = s1.split(" ");
String origin = coordinates[0];
String dest = coordinates[1];
while (!validCoordinate(origin, dim) && !validCoordinate(dest,dim)) {
System.out.println("ERROR: Please enter valid coordinate pair separated by space.");
String s2 = stdin.nextLine();
String[] coordinates2 = s2.split(" ");
String origin2 = coordinates[0];
String dest2 = coordinates[1];
}
return new String[0];
}
我创建了一个辅助函数validCooperative(String, int)
来检查有效性。
我该如何修复我的代码?
最佳答案
您应该考虑“do-while”循环,因为无论条件是否满足,您都希望运行代码一次。然后,在循环结束时,您可以检查条件是否满足。如果没有满足,就会再次运行。例如:
public static String[] positionQuery(int dim) {
boolean errorEncountered = false;
String[] coordinates;
Scanner stdin = new Scanner(System.in);
do {
if(errorEncountered)
System.out.println("ERROR: Please enter valid coordinate pair separated by space.");
else {
System.out.println("Provide origin and destination coordinates.");
System.out.println("Enter two positions between A1-H8:");
}
String s1 = stdin.nextLine();
coordinates = s1.split(" ");
String origin = coordinates[0];
String dest = coordinates[1];
if(!validCoordinate(origin, dim) || !validCoordinate(dest,dim) || coordinates.length != 2) //makes sure there's only 2 coords
errorEncountered = true;
else
errorEncountered = false;
} while (errorEncountered);
return coordinates;
}
在此示例中,我冒昧地删除了 Scanner test_in
输入,因为您没有使用它。
我还注意到您返回的 String[]
错误。如果您只想返回由 split()
生成的 String[]
,则应该返回该变量。不创建新的String[]
(参见上面的示例)。
这个循环(像所有循环一样)也可以通过 while(true)
来完成,它会在正确的条件下中断或返回。然而,这些有时被认为是不好的做法(请参阅 Are "while(true)" loops so bad? ),因为当您学习编写更复杂的代码时,一堆 break
或 return
可能会导致代码非常困惑且难以阅读。因此,您最好养成使用 boolean 值的习惯。
关于java - 如何循环问题直到从扫描仪得到答案?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60229901/