Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ArrayList input java

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);
    }
  }
}
like image 510
BLL27 Avatar asked Aug 21 '12 13:08

BLL27


4 Answers

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);
}
like image 159
posdef Avatar answered Nov 04 '22 12:11

posdef


I'd rather iterate over scanner and just add to a list:

List<Integer> list = new ArrayList<Integer>();
while(scanner.hasNextInt())
      list.add(scanner.nextInt());
}

then sort it.

like image 36
Piotr Gwiazda Avatar answered Nov 04 '22 13:11

Piotr Gwiazda


You need to use ArrayList add method

Example:

arraylist.add(nextVale);

You don't need to do for loop while using arraylist. As you add content, list size will increase automatically.

like image 28
kosa Avatar answered Nov 04 '22 12:11

kosa


First if you have an ArrayList, you would not use [] to access/set the elements. That's for arrays, which is different from an ArrayList. You would use the add method,

Second, you need to sort the ArrayList. Check out Collections.sort in the API.

Finally, to iterate over a List, there are many constructs available. One of the most common is..

List<Integer> numbers = new ArrayList<Number>();

numbers.add(1);
numbers.add(2);
...

for (Integer number : numbers) {
   System.out.println(number);
}
like image 30
hvgotcodes Avatar answered Nov 04 '22 13:11

hvgotcodes