-1

i am working to get the average of the temperature input given by user and this is my code so far but i am getting "Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1" , i don't understand where did i do wrong.

import javax.swing.JOptionPane;
public class JavaApplication1 {
    static double [] weekdays= new double[6];
    static String[] weekdaysNames = new String[]{"Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"};

    public static void promptTemp(){


        for(int i=0;i<weekdays.length;i++){
         for(int j=6;j<weekdaysNames.length;j--){
            weekdays[i] =Double.valueOf(JOptionPane.showInputDialog(null, "Please enter" + weekdaysNames[j] + "temperature?",
                    "TempApp", JOptionPane.QUESTION_MESSAGE));



        }

        }
        }

    public static double calcAverage(double [] value){

        double sum=0.0;

        for(int i=0;i<value.length;i++){
            sum=sum+value[i];
        }
        double average = sum/(value.length);
        return average;


    }



    public static void main(String[] args) {
        promptTemp();
        double k=calcAverage(weekdays);
                System.out.println(k);


    }

}
jacee
  • 41
  • 6

2 Answers2

0

The second for loop is the problem. j is starting at 6 and counting down. But j will always be less than weekdaysNames.length and it will go to -infinity, so that's why you're getting an ArrayIndexOutOfBounds

  for(int i=0;i<weekdays.length;i++){
     for(int j=6;j<weekdaysNames.length;j--){
ControlAltDel
  • 33,923
  • 10
  • 53
  • 80
  • i tried giving various logic for the loop but i am still getting the ava.lang.ArrayIndexOutOfBoundsException: -1 error, could you please help – jacee Mar 17 '17 at 20:28
  • That is why I closed your question as Duplicate. Don't make experiments. Read the content in that linked question and learn what that means! You solve this problem by understanding what your loops are doing – GhostCat Mar 18 '17 at 01:42
-1

problem in your 2nd for loop which is always less than weekdaysName.length which cause ArrayIndexOutOfBounds. one simple solution to get ride this problem is to change the size of weekdays array into [7] and use only one for loop.

Omore
  • 614
  • 6
  • 18