我正在尝试用对象填充 ArrayList

I'm trying to fill an ArrayList with Objects

我正在尝试用包含整数的对象填充 ArrayList,并将其转换为对象数组,从那里我可以确定我的对象数组中的最高整数值。但是由于某种原因,当我达到可以相互比较值的程度时,我已经丢失了一半的 ArrayList 或 Array of Objects。

import java.util.Scanner;
import java.util.ArrayList;
import java.util.Collections;
public class Exercise11_04
{
   public static void main(String [] args)
   {
       System.out.println("Enter a sequence of integers ending in 0: \n");
       Scanner input = new Scanner(System.in);  
       ArrayList<Integer> intList = new ArrayList<Integer>();

       while(input.nextInt() != 0)
       {
           intList.add(new Integer(input.nextInt()));
       }//end filler loop
       System.out.println(max(intList));
       arrayContents(intList);
   } 

   public static Integer max(ArrayList<Integer> list)
   {
       int maxIntIndex = 0;

       Integer[] integers = new Integer[list.size()];
       integers = list.toArray(integers);
       for(int index = 0; index < integers.length; index++ )
       {
           if(integers[index].getValue() >= integers[maxIntIndex].getValue()  )
           {
               maxIntIndex = index;
           }
       }
       return integers[maxIntIndex];
   }
   class Integer
   {
       private  int integer;

       Integer() {this(0);}
       Integer(int integer) {this.integer = integer;}
       public int getValue() {return this.integer;}
       public String toString()
       {
           return "The max value is: " + getValue();
       }//
}//end 

我尝试使用此方法查看数组的值

public static void arrayContents(ArrayList<Integer> list)
{
    Integer[] integers = new Integer[list.size()];
    integers = list.toArray(integers); 
    for(int index = 0; index < integers.length; index++)
    {
        System.out.println("The index is: " + index + " .The value is: " + integers[index].getValue());
    }
}

您在第一个循环中每次迭代使用 input.nextInt() 两次;一次测试该值是否为零,一次添加到您的列表中。因此,一半的值与 0 进行比较,另一半被添加到列表中。

只读一遍:

int v;
while ( (v = input.nextInt) != 0)
    intList.add(v);