Java Array Index Out of Borders

I am just starting a division in arrays, and I was provided with sample code that could be turned off for this main introductory program for arrays. Essentially, all I have to do is make two arrays that request temperature on that day of the week. After collecting the information, he simply spits it back into a line like this.

Monday's temperature was 16 degrees

Tuesday's temperature was 18 degrees

... etc.

From what I understood from the code of the code that I received, I am doing everything right. But when I try to run the program (in Netbeans) I get this error.

"Exception in thread" main "java.lang.ArrayIndexOutOfBoundsException: 7 at temperatures. Temperatures .main (Temperatures.java:27) Java Result: 1"

Here is the code:

public static void main(String[] args)throws IOException { // TODO code application logic here BufferedReader br = new BufferedReader (new InputStreamReader (System.in)); String temp[]= new String[7]; String day[]= new String[7]; day[1]=("Monday"); day[2]=("Tuesday"); day[3]=("Wednesday"); day[4]=("Thursday"); day[5]=("Friday"); day[6]=("Saturday"); day[7]=("Sunday"); for (int i=0; i <7; i++){ System.out.println("Please enter the temperature for" + day[i]); temp[i]=br.readLine(); } for (int i=0; i <7; i++){ System.out.println("The high temperature on " + day[i]+ " was "+ temp[i]); } } } 
+6
source share
5 answers

Arrays start from scratch (<is a link to an article that explains why). Thus, assigning your first value as day[1]=("Monday"); is a problem, it should be day[0]=("Monday"); Hope that helps

+6
source

Arrays in Java start at position 0, not at position 1. So, if you initialize it to 7, then Monday is 0 and Sunday is 6. There is no index 7.

+4
source

Starting starter at 0,

try it

  day[0]=("Monday"); day[1]=("Tuesday"); day[2]=("Wednesday"); day[3]=("Thursday"); day[4]=("Friday"); day[5]=("Saturday"); day[6]=("Sunday"); 

and if you change this loop

 for(int i=0; i < 7; i++){ System.out.println("Please enter the temperature for" + day[i]); temp[i]=br.readLine(); } 

for this

 for(int i=0; i < day.length(); i++){ System.out.println("Please enter the temperature for" + day[i]); temp[i]=br.readLine(); } 

I hope to help you.

+1
source

This is because your array begins with 1, ends with 7. If your array is 7, the last index should be less than the length of the array. In your case, the array sees that you declared it for 7 elements, but inserted 8 positions. So run the array from 0, end it with 6

0
source

If Array is "N", the boundaries of this array are 0 and "N-1". In your case, the boundary arrays are 0 and 6. But you are trying to write the value to an array [7] that does not exist.

0
source

Source: https://habr.com/ru/post/916017/


All Articles