Reputation: 19
I am wondering how to display the total number of rainfall that I took in from user input and add them outside of the loop. This is what I have:
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
}
}
I have everything I need it's just I take in the rainfall, but I don't know how to add all the rains I take in and add them to be displayed outside the loop where I have the line down there. I have a feeling I'm just over looking something simple...
Upvotes: 0
Views: 1084
Reputation: 30
Initialize your variables with 0 and do what @Juned Ahsan said
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);
}
}
Upvotes: 0
Reputation: 68725
Probably you just need to replace this:
rain= keyboard.nextInt();
with
rain += keyboard.nextInt();
Upvotes: 2