【问题标题】:Add numbers from inside a loop to display total outside. Java从循环内部添加数字以显示外部总数。爪哇
【发布时间】:2014-03-20 02:27:14
【问题描述】:

我想知道如何显示我从用户输入中获取的降雨总数并将它们添加到循环之外。这就是我所拥有的:

import java.util.Scanner;


public class SecretName {
public static void main(String args[]) {
    Scanner keyboard = new Scanner(System.in);
    int year;
    int rain;
    int count = 0;
    String[]names={"January ","February "};


    System.out.println("Enter the number of years: ");
    year= keyboard.nextInt();

    while (count < year) {


        System.out.println("For year "+ count);


        for(int i = 0; i < names.length; i++){
            System.out.println("Enter the inches of rainfall for "+ names[i]+":");
            rain= keyboard.nextInt();
        }
        count++;

    }
    int numMonths = names.length * year;
    System.out.println("Number of months "+ numMonths);
    System.out.println("Total rainfall "+ rain); //Won't work obviously


}
}

我有我需要的一切,只是我吸收了降雨,但我不知道如何添加我吸收的所有降雨并将它们添加到循环之外,我在那里有线。 我有一种感觉,我只是在看一些简单的东西......

【问题讨论】:

    标签: java loops add


    【解决方案1】:

    可能你只需要替换这个:

            rain= keyboard.nextInt();
    

            rain += keyboard.nextInt();
    

    【讨论】:

    • 按照您所说的将 + 添加到它时给我一个错误。除非您知道我不知道的事情,否则不确定这是否正确。
    【解决方案2】:

    用 0 初始化你的变量并按照@Juned Ahsan 所说的去做

    import java.util.Scanner;
    
    
    public class SecretName {
    public static void main(String args[]) {
        Scanner keyboard = new Scanner(System.in);
        int year = 0;
        int rain = 0;
        int count = 0;
    String[]names={"January ","February "};
    
    
    System.out.println("Enter the number of years: ");
    year= keyboard.nextInt();
    
    while (count < year) {
    
    
        System.out.println("For year "+ count);
    
    
        for(int i = 0; i < names.length; i++){
            System.out.println("Enter the inches of rainfall for "+ names[i]+":");
            rain += keyboard.nextInt(); // Is the same as rain = rain + keyboard.nextInt();
        }
        count++;
    
    }
    int numMonths = names.length * year;
    System.out.println("Number of months "+ numMonths);
    System.out.println("Total rainfall "+ rain);
    
    
    }
    }
    

    【讨论】:

    • 和我想的一样……简单到看不出来。谢谢,我很感激。
    猜你喜欢
    • 1970-01-01
    • 2015-02-15
    • 1970-01-01
    • 2012-05-22
    • 1970-01-01
    • 2013-11-29
    • 2020-04-04
    • 2020-06-04
    • 1970-01-01
    相关资源
    最近更新 更多