-1

这是我到目前为止编写的代码,我想添加每只老鼠解决的总数,但它显示的数量不正确。

鼠标 1 解决了多少个迷宫?4

鼠标 2 解决了多少迷宫?0

老鼠3解决了多少迷宫?1

鼠标 4 解决了多少迷宫?4

老鼠 1 解决了多少个迷宫?2

老鼠 2 解决了多少个迷宫?3

老鼠 3 解决了多少个迷宫?0

老鼠 4 解决了多少个迷宫?4

鼠标解决了 8。老鼠解决了 8

import java.util.Random;

public class ratloop {

public static void main(String[] args) {
        mazeRun();
        System.exit(0);
                                    }
        public static void mazeRun()
        {
            Random randomGenerator = new Random();
            int mouseTest;
            int mouseSolved = 1;
            for (mouseTest= 1; mouseTest <=4; mouseTest++)
                {
                    mouseSolved = randomGenerator.nextInt(5);
                    System.out.println("How many mazes did mouse " + mouseTest + " solve? " + mouseSolved);
                    mouseSolved = mouseSolved + mouseTest;
                }

                int ratTest;
                int ratSolved = 1;
                for (ratTest= 1; ratTest <=4; ratTest++)
                {
                    ratSolved = randomGenerator.nextInt(5);
                    System.out.println("How many mazes did rat " + ratTest + " solve? " + ratSolved);
                    ratSolved = ratSolved + ratTest;    
                }

                System.out.println("The mouse solved " + mouseSolved + " . And the rats solved " + ratSolved);

        }

}
4

2 回答 2

1

如果您在循环中添加数字,请不要将循环索引与您正在操作的数字混合。

int mouseSolvedTotal = 0;
for (int mouseTest = 1; mouseTest <= 4; mouseTest++) {
  int mouseSolved = randomGenerator.nextInt(5);
  System.out.println("How many mazes did mouse " + mouseTest + " solve? " + mouseSolved);
  mouseSolvedTotal += mouseSolved;
}

int ratSolvedTotal = 0;
for (int ratTest= 1; ratTest <= 4; ratTest++) {
  int ratSolved = randomGenerator.nextInt(5);
  System.out.println("How many mazes did rat " + ratTest + " solve? " + ratSolved);
  ratSolvedTotal += ratSolved;    
}
于 2013-10-14T18:24:28.753 回答
0

这一行:

mouseSolved = randomGenerator.nextInt(5);

每次通过循环将您的计数重置为随机数。您需要为此使用不同的变量。

造成您麻烦的部分原因是您正在使用mouseSolved两种不同的东西。您正在使用它来存储已解决的迷宫总数,并且您正在使用它来存储在循环的每次迭代中解决的迷宫数量。它不能同时做到这两点。你需要两个变量,比如mouseSolvedTotalmouseSolvedCurrent来处理这两个想法。

于 2013-10-14T18:01:31.540 回答