Java if-else question

copelandtml

Baseband Member
Messages
45
I'm trying to code a program to calculate the average rainfalls over a year. This is my code:

import java.util.Scanner;
public class C_C_PartC
{
public static void main(String[]args)
{
//title
System.out.println("**This is Craig Copeland's Rainfall Averager**");
System.out.println("This program will calculate the average rainfall over the year\n");

//create Scanner
Scanner input = new Scanner(System.in);

//create variables
int spring = 0;
int summer = 0;
int autumn = 0;
int winter = 0;
double averageRainfall = 0.0;
int totalRainfall = 0;

//prompt users for input
System.out.print("Enter your rainfall for spring...");
spring = input.nextInt();

System.out.print("Enter your rainfall for summer...");
summer = input.nextInt();

System.out.print("Enter your rainfall for autumn...");
autumn = input.nextInt();

System.out.print("Enter your rainfall for winter...");
winter = input.nextInt();

//calculate average
totalRainfall = spring + summer + autumn + winter;
averageRainfall = totalRainfall / 4;

// if-else statement and final printout
if(averageRainfall >=30.0)
{
System.out.println("Your average monthly rainfall is "+ averageRainfall +" mm of rain...need an umbrella?");
}
else if(averageRainfall >=20.0)
{
System.out.println("Your average monthly rainfall is "+ averageRainfall +" mm of rain...this is good for the garden!");
}
else if(averageRainfall >=10.0)
{
System.out.println("Your average monthly rainfall is "+ averageRainfall +" mm of rain...your lawn is looking thirsty.");
}
else
{
System.out.println("Your average monthly rainfaill is "+ averageRainfall +" mm of rain... you must drive a camel");
}



}//end main method
}//end class

Now that runs just fine, but I want to make the if-else more specific such as:
else if(averageRainfall >=10.0 && <20.0)

Now when I did that, the program would not compile and I had about 20+ errors. Something to do with double and boolean variables not being allowed to use the and(&&) and or(||) operators in an if-else statement.

Any help would be great!
Thanks!
 
You have to specify the variable both times like this:

Code:
else if(averageRainfall >=10.0 && averageRainfall <20.0)
 
Ok, thanks for the reply...kinda feel like an idiot now lol but I guess now I know for next time. Is that only for double and boolean variables or is that for all variables?
 
alright, thanks again....another quick question if you don't mind.
when creating variables is it good to initialize them to something (0 or "") such as:
int number = 0;
String name = "";
 
Generally yes. If it's a local variable you can't do anything without initialising it anyway, if it's a field it'll automatically get set to a default value (but it's better to explicitly define this to state your intent.)
 
Back
Top Bottom