ArrayList input java
Asked Answered
F

8

7

I'm looking at the problem:

Write a program which reads a sequence of integers and displays them in ascending order.

I'm 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 I'm 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);
        }
    }
}
Fraise answered 21/8, 2012 at 13:43 Comment(3)
As soon as you're populating a list from scanner you whould probably iterate over scanner and just add to a list.Mendicity
Please make sure you read this when asking homework questions (as most of your questions seem to be) meta.stackexchange.com/questions/10811/…Intercessory
@Dave: the line: List numbers = new ArrayList(); will give rise to warnings based on raw types. Since you know (or assume) that the numbers will be integers you should define the list with type information, see my answer (or Piotr's).Ashraf
A
9

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);
}
Ashraf answered 21/8, 2012 at 13:48 Comment(2)
Thanks. How do I exit the while loop after entering a line of integers, ie not enter an infinite amount of integers? Im sure theres an easy way to do it,its just confusing me at the moment.Fraise
The sc.hasNextInt() should return false when the next token is not an integer (better put, when the next token cannot be parsed as an integer). See the documentation: docs.oracle.com/javase/7/docs/api/java/util/…Ashraf
M
5

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.

Mendicity answered 21/8, 2012 at 13:47 Comment(0)
R
2

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.

Renettarenew answered 21/8, 2012 at 13:44 Comment(0)
C
1

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);
}
Cairngorm answered 21/8, 2012 at 13:47 Comment(0)
V
0
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class sortArrayList {

    public static void main(string args[]) {
        List<Integer> arrList = new ArrayList<Integer>();
        while (scanner.hasNextIint()) {
            arrList.add(scanner.nextInt());
        }
        Collections.sort(arrList);
    }
}
Vitta answered 21/8, 2012 at 13:57 Comment(1)
You need to not use back ticks when posting code over several lines. You also need to use a better standard of code - for example Java class names should have a capital letter to start.Intercessory
C
0

It is not that hard. Since you are using Array List, it is very easy!

import java.util.*;
class Arr{
public static void main(String args[]){
Scanner sc=new Scanner(System.in);//initializing scanner class
String cont="";//String to check whether the user wants to input anymore numbers or not
List<Double> n=new ArrayList<Double>();//List that will store our numbers
while(!(cont.equals("no"))){//taking continuous input

        System.out.println("Enter number:");
        n.add(sc.nextDouble());

        System.out.println("Do you want to continue?(type 'yes'/'no')");
        cont=sc.next();
    }
Collections.sort(n);//sorts your ArrayList
System.out.println("Sorted list:");
for (Double value : n) {//displaying sorted list
        System.out.println( value);
}
}
}
Carlita answered 19/12, 2021 at 7:8 Comment(0)
V
0

You can also use a for loop:

ArrayList<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < 5; i++) {
    list.add(sc.nextInt());
}
Varied answered 7/1, 2022 at 6:38 Comment(0)
H
-1
 List<Integer> list1 =  new ArrayList<>();
    try (Scanner sc = new Scanner(System.in)) {
        int n=sc.nextInt();

        for(int i=0;i<n;i++){
            list1.add(sc.nextInt());
        }
    }
    for(int n1:list1){
        System.out.print(n1+" ");
    }
Hydrocellulose answered 16/3 at 16:56 Comment(2)
As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.Abundance
Answers that contain only code are generally considered poor quality. Also, the question states that the list of numbers be displayed in ascending order and I don't see how your code achieves that so I would argue that your answer is not correct. Nonetheless incorrect answers are still considered to be valid answers on this website. You can edit your answer and fix the code and also add some explanation as to how your code works, for example referencing the javadoc for the classes and methods in your code.Desinence

© 2022 - 2024 — McMap. All rights reserved.