如何从For循环中添加结果 - Java

时间:2013-10-14 17:59:16

标签: java

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

鼠标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);

        }

}

2 个答案:

答案 0 :(得分: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;    
}

答案 1 :(得分:0)

这一行:

mouseSolved = randomGenerator.nextInt(5);

每次循环都会将计数重置为随机数。你会想要使用另一个变量。

导致您遇到麻烦的部分原因是您正在使用mouseSolved来处理两件不同的事情。您正在使用它来存储已解决的迷宫总数,并且您正在使用它来存储在循环的每次迭代中求解的迷宫数量。它不能同时做到这两点。您需要两个变量,例如mouseSolvedTotalmouseSolvedCurrent来处理这两个想法。