如何在方法中返回for语句的总和

我正在尝试编写总结骰子总数的代码(不要担心骰子 [i] 的输出,我只需要返回总和)。


public static int displayAndTotalDice(int[] dice) {

        int i;

        for (i = 0; i < dice.length; ++i) {

            System.out.println("Dice " + i + " rolls: " + dice[i]);

            int sum = 0 + dice[i];

        }

        return sum;

    }

我收到错误“总和无法解析为变量。” 有什么建议?


慕仙森
浏览 148回答 2
2回答

繁华开满天机

sum 应该限定范围(并初始化),以便在循环后可以访问它。public static int displayAndTotalDice(int[] dice) {&nbsp; &nbsp; int i, sum = 0;&nbsp; &nbsp; for (i = 0; i < dice.length; ++i) {&nbsp; &nbsp; &nbsp; &nbsp; System.out.println("Dice " + i + " rolls: " + dice[i]);&nbsp; &nbsp; &nbsp; &nbsp; sum += dice[i];&nbsp; &nbsp; }&nbsp; &nbsp; return sum;}

慕村9548890

sum在for循环中使用变量并返回其值之前,将变量的声明移动到方法级作用域中。您收到错误 “总和无法解析为变量”。因为你sum在for循环中声明,所以只在循环中可见。public static int displayAndTotalDice(int[] dice) {&nbsp; &nbsp; &nbsp; &nbsp; int i;&nbsp; &nbsp; &nbsp; &nbsp; int sum = 0;&nbsp; &nbsp; &nbsp; &nbsp; for (i = 0; i < dice.length; ++i) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println("Dice " + i + " rolls: " + dice[i]);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; sum += dice[i];&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return sum;&nbsp; &nbsp; }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java