我有一个计算机科学课的项目,我们正在制造战舰.该计划的一部分是我们确保玩家放下的棋子不会脱离棋盘.
我已经做了一个方法来检查它是否脱离了董事会:
private static boolean test(String s, int row, int column,int spaces)
{
if(s.equals("right")&&column+5<=10)
{
return true;
}
if(s.equals("up")&&row-spaces>=0)
{
return true;
}
if(s.equals("left")&&column-spaces>=0)
{
return true;
}
if(s.equals("Down")&&row+spaces<=10)
{
return true;
}
return false;
}
Run Code Online (Sandbox Code Playgroud)
但是,一旦我得到它打印出一条错误信息,我不知道如何制作它以便程序可以重新接收该片段的新位置,而不在if和if语句中放入if语句声明(以及开启和关闭),因为您需要检查新位置以确保它不会脱离电路板.
这是我获得比赛位置的部分(虽然我认为你不需要它)
Scanner sonic= new Scanner(System.in);
System.out.println("Please input the row where you want the aircraft carrier (5 spaces) to begin: ");
int beginrow = sonic.nextInt();
System.out.println("Please input the column where you want the aircraft carrier (5 spaces) to begin: ");
int begincolumn = sonic.nextInt();
System.out.print("Please input what direction (up, down, left, right) \nyou want your battle ship to face, making sure it doesn't go off of the board.");
String direction = sonic.next();
Run Code Online (Sandbox Code Playgroud)
这是我用来检查/放置碎片的if语句之一
if(direction.equals("left")&&test("left",beginrow,begincolumn,5))
{
for(int i = beginrow; i>beginrow-5; i--)
{
battleship[begincolumn-1][i-1] = ('a');
}
}
else if(!test("left",beginrow,begincolumn,5))
{
System.out.println(" ");
System.out.println("*****ERROR: your piece goes off the board, please re-enter your position and direction*****");
}
Run Code Online (Sandbox Code Playgroud)
这可能是重复的,但我不知道如何改写我的搜索以找到我想要的内容.(所以,如果有人能指导我找到合适的文章,那也很好)
第一步,将输入验证与基于该输入采取的操作分开 - 您已经在单独的函数中拥有验证逻辑,因此这很容易。然后弄清楚在输入无效的情况下需要做什么 - 在您的情况下,您需要请求新的输入,直到获得有效的位置:
do {
System.out.println("Please input the row where you want the aircraft carrier (5 spaces) to begin: ");
beginrow = sonic.nextInt();
System.out.println("Please input the column where you want the aircraft carrier (5 spaces) to begin: ");
begincolumn = sonic.nextInt();
System.out.print("Please input what direction (up, down, left, right) \nyou want your battle ship to face, making sure it doesn't go off of the board.");
direction = sonic.next();
} while (!test(direction, beginrow, begincolumn, 5))
Run Code Online (Sandbox Code Playgroud)
之后,您就知道您已经获得了有效的职位。
我的下一步可能是将描述棋盘上的一艘船(即,,,也可能)所需的信息分组beginrow到一个单独的对象中 - 可能命名begincolumn为。directionsizeShip
| 归档时间: |
|
| 查看次数: |
404 次 |
| 最近记录: |