• Quick note - the problem with Youtube videos not embedding on the forum appears to have been fixed, thanks to ZiprHead. If you do still see problems let me know.

Needs some Java help.

Achán hiNidráne

Illuminator
Joined
Jun 23, 2004
Messages
3,974
Hey all:

Working on some Java class homework and I need some help. I'm supposed to write a program that asks for a month and creates a one dimensional array that holds the temperature for each day of the month then it creates a printout of each day of the month then gives the average temp. I'm I've got the first part done, but it blows up with an out of bounds exception when I try to run the second part. Here's my code:

public class temperature
{
private int dayTemp[];
private String month;

public void temperatureMethod()
{

System.out.println("Please type in the month:");
java.util.Scanner scan = new java.util.Scanner(System.in);
String month = scan.next();
if (month.equals("February")){
dayTemp = new int[28];
}
else if(month.equals("April") || month.equals("June") || month.equals("September") || month.equals("November")){
dayTemp = new int[30];
}
else if (month.equals("January") || month.equals("March") || month.equals("May") || month.equals("July") || month.equals("August") || month.equals("October") || month.equals("December")){
dayTemp = new int[31];
}
else {
System.out.println("Please enter a valid month.");
}
int i=0;
int j=1;
while(i < dayTemp.length){
System.out.println("Enter temperature for day: " + j );
dayTemp = scan.nextInt();
i++;
j++;
}
}

public void printTempMethod()
{
System.out.println("Month: " + month);
int highTemp=0;
int lowTemp=0;
int averageTemp=0;
System.out.println("Month: " + month);
int k=0;
int l=0;
while(l <= dayTemp.length){
System.out.println(dayTemp[k]); <---Blue J says THIS is the point where the out of bound exception is occurring.
k++;
l++;
}
for (int m = 0; m < dayTemp.length; m++){
averageTemp += dayTemp[m];
}
System.out.print("Average: " + averageTemp);


Can anyone give me a clue what I'm doing wrong?
 
Last edited:
"while l <= dayTemp.length"

you are going 1 past the bounds of the array.
 
Just curious why you're using two different variables here when they both start at 0 and increment each time through that while loop.

The first time you go through it, one of your variable start at 1, the other at 0:
int i=0;
int j=1;
while(i < dayTemp.length){
System.out.println("Enter temperature for day: " + j );
dayTemp = scan.nextInt();
i++;
j++;


While the second time, you start both at 0:

int k=0;
int l=0;
while(l <= dayTemp.length){
System.out.println(dayTemp[k]); <---Blue J says THIS is the point where the out of bound exception is occurring.
k++;
l++;

My java and addressing arrays in it ain't that great, but did you need to have l = 1 like the first loop?
 

Back
Top Bottom