Im looking at the problem:
Write a program which reads a sequence of integers and displays them in ascending order.
Im creating an ArrayList (which I am new to) and I want to populate with integers input from the command line. With an array I could use a for loop with
for (int i =0; i < array.length; i++) { array[i] = scanner.nextInt();
but with an ArrayList of unbounded size Im not sure how to process the input?
EDIT:
class SortNumbers { public static void main(String[] args) { List numbers = new ArrayList(); Scanner scanner = new Scanner(System.in); System.out.println("Enter some numbers."); while (scanner.hasNextInt()) { int i = scanner.nextInt(); numbers.add(i); } } }
Advertisement
Answer
The idea with using ArrayList is to avoid the deterministic iteration counts. Try something like this:
ArrayList<Integer> mylist = new ArrayList<Integer>(); while (sc.hasNextInt()) { int i = sc.nextInt(); mylist.add(i); }