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.

Goibniu
  • 2,213
  • 2
  • 35
  • 34
  • 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. – Olivier Depriester May 01 '20 at 18:45
  • @OlivierDepriester Actually, I'm pretty sure `Scanner#nextInt` can handle integers separated by whitespace – user May 01 '20 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 – Olivier Depriester May 01 '20 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 – user May 01 '20 at 19:09

1 Answers1

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.

Harshal Parekh
  • 4,830
  • 4
  • 13
  • 34