Need help with array code
Hi I'm just beginning to learn and work with arrays and I was going to try a program that ask the user to enter 8 hourly temperatures and let the program output these temperatures.
When I run the program and enter the 8 temperatures this is what my prompt says:
'Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 8 at TemperatureArray.main(TemperatureArray.java:18)'
I have never seen this before.. my code compiles fine but here it is also:
Code :
import java.util.*;
public class TemperatureArray
{
static Scanner console = new Scanner(System.in);
public static void main(String[] args)
{
int[] temp = new int[8];
int avg;
int index;
System.out.println("Enter 8 numbers: ");
for (index = 0; index < temp.length; index++)
temp[index] = console.nextInt();
System.out.print(temp[index] + " ");
}
}
Re: Need help with array code
You forgot to put the braces around the for loop. Also, as a good programming practice, don't declare for loop counters outside of the for loop.
Code :
// ex.
for (int index = 0; index < temp.length; index++)
{
temp[index] = console.nextInt();
System.out.print(temp[index] + " ");
}
Re: Need help with array code
Thanks a lot for the tip and correction.. now I have to figure out how to get the output to print after I type all of the input lol
It's a shame I've had to pay $80 for a book full of errors. My book was saying to print an array do a for loop like:
Code :
for (index = 0; index < array.length; index++)
System.out.print(array[index] + " ");
Re: Need help with array code
That's actually correct. Again, from a programming style I prefer to put the index declaration inside the for loop as a second check just to make sure I don't use that variable anywhere else (at least not without re-declaring it).
If you want to have the display after, simply use two loops: one to get the input from the user, and the second loop to print out the display.