2

I am writing a program that will take user input and sort it in ascending order or descending order depending on what they choose. I tried using a simple array but it didn't work properly with the array sort methods so I then tried an ArrayList. This seems to work except for the fact that it only reads the first int that is typed by the user. I tried the addAll method but it appears that only works for collections and not variables.

This is my code:

import java.util.Scanner;
import java.util.ArrayList;
import java.util.Collections;
public class ElevenThree {
    public static void main (String[] args) {
        Scanner scan = new Scanner(System.in);
        ArrayList<Integer> arrayList = new ArrayList<Integer>();
        int size = 0;
        int type = scan.nextInt();
        if(type == 0) {
            size = scan.nextInt();
            arrayList.add(scan.nextInt());
            Collections.sort(arrayList);
        }
        if (type == 1) {
            size = scan.nextInt();
            arrayList.add(scan.nextInt());
            Collections.sort(arrayList, Collections.reverseOrder());
        }
        System.out.println(arrayList);
    }
}

Input:

0
9
4 3 6 8 9 2 1 5 7

Output:

[4]

By the way, I have the size variable there because this is an assignment through a program that automatically inputs the size variable so it needs to be there even if it doesn't affect the program in any way.

4
  • Your issue is the use of scan.nextInt(). When you type 4 3 6 8 9 2 1 5 7, you send a string "4 3 6 8 9 2 1 5 7" and no more an int. Then it's up to you to split this string. Commented May 1, 2020 at 18:45
  • @OlivierDepriester Actually, I'm pretty sure Scanner#nextInt can handle integers separated by whitespace Commented May 1, 2020 at 18:55
  • Yes it can but not as an integer array because it will extract the tokens until if finds one that is not numeric. Look at @Harshal Parekh answer Commented May 1, 2020 at 19:07
  • @OlivierDepriester Ok, I thought you were recommending using scan.next() and then String#split, followed by Integer.parseInt for all of the substrings Commented May 1, 2020 at 19:09

1 Answer 1

3

When you say nextInt() it only takes the first integer which is 4.

You need to take the input in a loop.

for (int i = 0; i < size; i++) {
    arrayList.add(scan.nextInt());
}

Note: Entering integers in a line will allow you to enter unlimited integers, but it will only accept the n integers where n is the size. The program will stop after n inputs if you enter each on a different line.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.