英文:
Why does this always return positive score? Simple code
问题
public static void main(String [] args){
int[][] Board = new int[7][7];
int kills = 0;
Random random = new Random();
int x = random.nextInt(7);
int y = random.nextInt(7);
int boat = Board[x][y];
Scanner input = new Scanner(System.in);
while (kills < 1){
System.out.println("Where is the boat? Enter 2 digits");
System.out.println(x+""+y);
int guessX = input.nextInt();
int guessY = input.nextInt();
if (boat == Board[guessX][guessY]){
kills = kills + 1;
System.out.println("Sinked!");
}
}
}
英文:
I'm building simple game which places a boat on random element of array (random x and y). The goal is to guess place (this x and y). But anything I type it always return guessed.
public static void main(String [] args){
int[][] Board = new int[7][7];
int kills = 0;
Random random = new Random();
int x = random.nextInt(7);
int y = random.nextInt(7);
int boat = Board[x][y];
Scanner input = new Scanner(System.in);
while (kills < 1){
System.out.println("Where is the boat? Enter 2 digits");
System.out.println(x+""+y);
int guessX = input.nextInt();
int guessY = input.nextInt();
if (boat == Board[guessX][guessY]){
kills = kills + 1;
System.out.println("Sinked!");
}
}
}
</details>
# 答案1
**得分**: 1
`int boat = Board[x][y]` 将会将 `boat` 设为零。这是这些数组的每个元素的值。
要添加一艘船,您实际上必须将数组的一个元素设置为一个值。
```c
int boat = 1;
Board[x][y] = boat;
(编辑:我现在不确定这是一个真正的问题,还是程序只是某种深夜的打字错误。)
英文:
int boat = Board[x][y]
is going to set boat
to zero. Which is the value of every element of those arrays.
To add a boat, you have to actually set one of the array elements to a value.
int boat = 1;
Board[x][y] = boat;
(Edit: and I'm not sure now if this is a real question or if the program is just some sort of late night typo.)
答案2
得分: 1
在代码中,您正在使用默认值(在Java中为int的0)初始化一个Board数组<br>然后,您只是将数组中的值与生成的随机索引处的用户输入索引数组值进行比较。<br>在这种情况下,两者都是零,因此每次都显示匹配。<br>
要使其工作,您可以将猜测的索引与随机生成的索引进行比较,以确定船的位置。<br>
英文:
in the code you are initializing a Board array with default value(0 in java for int)<br>
Then you are just comparing the value in the array at a random index generated against the user input index array value.<br>
In this case both are zero and hence it shows a match every time.<br>
To make it work you can compare the indices guessed against the indices randomly generated to designate the boat.<br>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论