ArrayList在循环后保持重置。我究竟做错了什么?

时间:2013-04-27 00:22:29

标签: java arrays loops arraylist while-loop

每次我遍历arrayList时,它都会自行重置。最终目标是制作一个程序,在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);
            }
        }
    }
}

2 个答案:

答案 0 :(得分:3)

您在循环的每次迭代中重新声明max。移动线

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

while循环之前和之前。

答案 1 :(得分:2)

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

每次你说ArrayList max = new ArrayList();

你创建了新的arraylist,确保你这样做并继续添加