我在编程方面比较新,希望您能够耐心等待。
我正在尝试编写一个战舰游戏,目前还没有使用OO技术,而是采用逐步处理的过程式编程方法进行。
我有一个读取要开火的坐标的方法,我想要验证这些坐标是否有效。有一种方法可以检查它们是否为数字,并且是否在正确的范围内,另一种方法则“应该”检查已经输入的内容。
问题在于,在进行while循环时,我无法跳出do while循环来继续执行,while部分采用了两个以逻辑或运算符连接的方法。在编写这些方法时,它们都能够完成其预期功能,但我不能确定检查坐标是否已被击中的方法是否正确。
如果您能提供任何方面的建议,那将不胜感激!
代码:
public static String inputCoords(List<String> coordsFired){
Scanner sc = new Scanner(System.in);
//Console c = System.console();
String coordsEntered;
do {
System.out.println("in do\\while");
System.out.println("Enter coordinates as 'x, y': ");
coordsEntered = sc.nextLine();
System.out.println("end of do\\while loop");
} while(!validateCoords(coordsEntered)
|| !coordsFiredAt(coordsEntered, coordsFired));
coordsFired.add(coordsEntered);
System.out.println("contents of List<String> coordsFired" + coordsFired);
return coordsEntered;
}
public static boolean validateCoords(String coordsEntered){
boolean results;
int x, y;
String strx = splitCoordsString(coordsEntered, 'x');
String stry = splitCoordsString(coordsEntered, 'y');
if (numericCheckCoordsFire(strx) && numericCheckCoordsFire(stry)) {
x = Integer.parseInt(strx);
y = Integer.parseInt(stry);
if (x > 25 || y > 25) {
results = false;
System.out.println("The dimensions of the board are 25 x 25, 'x,y' entered must be less than this. You entered '" + strx + "' for x and '" + stry + "' for y.");
} else {
results = true;
}
} else {
results = false;
System.out.println("Coords are supposed to be numbers... You entered '" + strx + "' for x and '" + stry + "' for y.");
}
System.out.println(results);
return results;
}
public static boolean coordsFiredAt(String coordsEntered, List<String> coordsFired) {
boolean results = false;
// go through each item in the list and compare against coordsEntered
for (String s : coordsFired) {
System.out.println("in for loop, printing iterated var" + s);
if (s.equals(coordsEntered)) {
// put these matched coordsFire into listHit
results = false;
} else {
System.out.println("already fired at " + coordsEntered);
results = true;
}
}
return results;
}