userJoe
userJoe

Reputation: 63

ArrayList keeps resetting after loop. what am I doing wrong?

Everytime I loop through the arrayList, it resets itself. Eventually the goal is to make a program that finds the mean of numbers in an arrayList

public class loops {
    public static void main(String[] args) {

        System.out.println("Do you want to calculate the most reoccuring answer?");
        System.out.println("enter 'yes' or 'no'");

        Scanner start = new Scanner(System. in );
        String starter = start.nextLine();
        boolean jax = true;

        while (jax == true && starter.equals("yes")) {
            Scanner answer = new Scanner(System. in );
            System.out.println("Enter the answer choice");
            int ans = answer.nextInt();

            ArrayList < Integer > max = new ArrayList < Integer > ();
            max.add(ans);

            Scanner goOn = new Scanner(System. in );
            System.out.println("Any other grades?");
            System.out.println("yes or no");
            String procced = goOn.nextLine();
            String str12 = "yes";
            String str113 = "no";


            if (procced.equals(str113)) {
                jax = false;
                System.out.print(max);
            }
        }
    }
}

Upvotes: 1

Views: 1330

Answers (2)

chans
chans

Reputation: 497

ArrayList <Integer> max = new ArrayList<Integer>(); 
max.add(ans);

everytime you say ArrayList max = new ArrayList();

you create new arraylist, make sure you do that once and keep adding

Upvotes: 2

user1447460
user1447460

Reputation:

You're redeclaring max in every iteration of the loop. Move the line

ArrayList <Integer> max = new ArrayList<Integer>(); 

To be before outside and before the while loop.

Upvotes: 3

Related Questions