java - 如何循环问题直到从扫描仪获得答案?
问题描述
我正在尝试循环询问坐标并从扫描仪获取输入。我想要求输入,直到坐标有效。但是,我对 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];
}
我创建了一个validCoordinate(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[]
错误。如果您只想返回由String[]
生成的split()
,则应该返回该变量。不做新的String[]
(见上面的例子)。
这个循环(像所有循环一样)也可以通过while(true)
在正确的条件下中断或返回来完成。但是,这些有时被认为是不好的做法(请参阅“while(true)”循环有那么糟糕吗?)因为当您学习编写更复杂的代码时,一堆break
' 或return
' 会使代码非常混乱且难以阅读. 因此,您最好养成使用布尔值的习惯。
推荐阅读
- julia - 在向量的参数向量上调度时出现 MethodError
- r - 如何获得唯一 ID 的因子级别
- java - 一个类已由 Java 运行时的更新版本编译
- python - 如何修改python假期库中的观察值
- python - Python文件上传使用S3签名?
- python - 使用 Selenium 单击第二个 img
- excel - Excel / SharedStrings 的排序算法
- java - Volley 没有收到 http 响应,但邮递员是
- javascript - REDUX:错误:操作可能没有未定义的“类型”属性。你有没有拼错一个常数?
- vee-validate - 规则中的 Vee-Validate v3 服务器端验证