为什么这总是返回正分数?简单代码

huangapple go评论108阅读模式
英文:

Why does this always return positive score? Simple code

问题

  1. public static void main(String [] args){
  2. int[][] Board = new int[7][7];
  3. int kills = 0;
  4. Random random = new Random();
  5. int x = random.nextInt(7);
  6. int y = random.nextInt(7);
  7. int boat = Board[x][y];
  8. Scanner input = new Scanner(System.in);
  9. while (kills < 1){
  10. System.out.println("Where is the boat? Enter 2 digits");
  11. System.out.println(x+""+y);
  12. int guessX = input.nextInt();
  13. int guessY = input.nextInt();
  14. if (boat == Board[guessX][guessY]){
  15. kills = kills + 1;
  16. System.out.println("Sinked!");
  17. }
  18. }
  19. }
英文:

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.

  1. public static void main(String [] args){
  2. int[][] Board = new int[7][7];
  3. int kills = 0;
  4. Random random = new Random();
  5. int x = random.nextInt(7);
  6. int y = random.nextInt(7);
  7. int boat = Board[x][y];
  8. Scanner input = new Scanner(System.in);
  9. while (kills &lt; 1){
  10. System.out.println(&quot;Where is the boat? Enter 2 digits&quot;);
  11. System.out.println(x+&quot;&quot;+y);
  12. int guessX = input.nextInt();
  13. int guessY = input.nextInt();
  14. if (boat == Board[guessX][guessY]){
  15. kills = kills + 1;
  16. System.out.println(&quot;Sinked!&quot;);
  17. }
  18. }
  19. }
  20. </details>
  21. # 答案1
  22. **得分**: 1
  23. `int boat = Board[x][y]` 将会将 `boat` 设为零。这是这些数组的每个元素的值。
  24. 要添加一艘船,您实际上必须将数组的一个元素设置为一个值。
  25. ```c
  26. int boat = 1;
  27. 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.

  1. int boat = 1;
  2. 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>

huangapple
  • 本文由 发表于 2020年8月25日 12:22:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/63572016.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定