1

每次我遍历 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);
            }
        }
    }
}
4

2 回答 2

3

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

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

在外部和while循环之前。

于 2013-04-27T00:25:22.533 回答
2
ArrayList <Integer> max = new ArrayList<Integer>(); 
max.add(ans);

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

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

于 2013-04-27T00:26:22.907 回答