Java 战舰项目问题
所以我一直在为学校做战舰项目,我为我的游戏制作了这个1-D板。到目前为止,我认为我的代码是正确的,但现在我被卡住了。在我的for-each循环中,由于它用我的飞船的三个值中的每一个来检查我的猜测,所以每次我猜测时,它都会打印我是否击中飞船三次。我正试着让我的程序打印我是否每次上船一次Java 战舰项目问题,java,arrays,foreach,Java,Arrays,Foreach,所以我一直在为学校做战舰项目,我为我的游戏制作了这个1-D板。到目前为止,我认为我的代码是正确的,但现在我被卡住了。在我的for-each循环中,由于它用我的飞船的三个值中的每一个来检查我的猜测,所以每次我猜测时,它都会打印我是否击中飞船三次。我正试着让我的程序打印我是否每次上船一次 public class Basic { public static int numGuess; public int guess; public int numHits = 0;
public class Basic
{
public static int numGuess;
public int guess;
public int numHits = 0;
private static int[] ships;
private boolean hitShip;
public static boolean shipSunk;
private int[]board = new int[5];
public Basic()
{
numGuess = 0;
hitShip = false;
shipSunk = false;
}
public static void setShips (int[] loc)
{
ships = loc;
}
public int Check(int z)
{
for(int cell : ships)
{
if(z == cell)
{
hitShip = true;
System.out.println("\nYou hit an enemy ship!");
numHits++;
numGuess++;
if(numHits == ships.length)
{
shipSunk = true;
System.out.println("\nYou sunk the enemy ship!");
System.out.println("the number of guesses it took you to sink the ship is " + numGuess/3);
break;
}
}
else
{
System.out.println("You've missed the enemy ship!");
}
}
return z;
}
}
import java.util.Scanner;
导入java.util.Random;
公共类基本酯
{
公共静态void main(字符串[]args)
{
Basic shipp=new Basic();//初始化基本类
int ship=(int)(Math.random()*5);//给ship一个介于1-5之间的随机值
int ship1;
int ship2;
智力猜测;
如果(发货而不是
import java.util.Scanner;
import java.util.Random;
public class BasicTester
{
public static void main(String[] args)
{
Basic shipp = new Basic(); //initalizes basic class
int ship = (int)(Math.random() * 5); // gives ship a random # between 1 - 5
int ship1;
int ship2;
int guess;
if(ship <= 2)
{
ship1 = ship + 1;
ship2 = ship + 2;
}
else
{
ship1 = ship - 1;
ship2 = ship - 2;
}
int[] locations = {ship, ship1, ship2};// sets array of locations
shipp.setShips(locations); // sets locations to ships in other class
Scanner guesss = new Scanner(System.in); // Scanner
do
{
System.out.println("\nTell me where the enemy ship is.");
guess = guesss.nextInt(); // gives guess the int from Scanner
int resultb = shipp.Check(guess); // puts the int guess through the check method
}
while(Basic.shipSunk == false);
}
}
在循环内部,应该在循环之前设置一个标志
else
{
System.out.println("You've missed the enemy ship!");
}
然后,当你对照三艘“飞船”进行检查时,你可以在找到命中目标时将此标志设置为“真”。最后,在循环后检查标志。如果仍然为假,则打印消息。你被卡在哪里?你尝试了什么?
hitIt = false;