Kobek
Kobek

Reputation: 1211

Java : Get only 1 line of integers from the console?

I recently picked up Java and I am having an issue with some console input.

Basically, I want to read in an array of ints from the console in a format like this :

1 2 3 4 5 6

I looked through some examples on the forums and decided to do this by using the scanner nextInt() method.

My code currently looks like this :

Scanner get = new Scanner(System.in);
List<Integer> elements = new ArrayList<>();

while (get.hasNextInt()) {           
        elements.add(get.nextInt());
    }

The problem with this code is that the while loop doesn't stop when I hit "Enter" on the console. Meaning that after I enter some numbers (1 3 5 7) and then hit enter, the program doesn't continue with execution, but instead waits for more integers. The only way it stops is if I enter a letter to the console.

I tried adding !get.hasNextLine() as a condition in my while loop, but this didn't help.

I would be very greatful, if anyone has an idea how can I fix this.

Upvotes: 0

Views: 2266

Answers (4)

abioticGirl
abioticGirl

Reputation: 188

If you want to read only one line the simpliest answer may be the best :)

Scanner in = new Scanner(System.in); String hString = in.nextLine(); String[] hArray = hString.split(" ");

Now, in array hArray you have all elements from input and you can call them like hArray[0]

Upvotes: 2

Yassin Hajaj
Yassin Hajaj

Reputation: 21975

You may use the following. User just has to enter each integer without pressing enter and press enter at the end.

Scanner get = new Scanner(System.in);
List<Integer> elements = Stream.of(get.nextLine().split(" "))
                               .map(Integer::parseInt)
                               .collect(Collectors.toList());

Upvotes: 0

Mohamed Kordufani
Mohamed Kordufani

Reputation: 1

Scanner get = new Scanner(System.in);
String arrSt = get.next();
StringTokinizer  stTokens = new StringTokinizer(arrSt," ");
int [] myArr = new Int[stTokens.countTokens()];
int i =0;
while(stTokens.hasMoreTokens()){
    myArr[i++]=Integer.parseInt(stTokens.nextToken());
}

Upvotes: 0

Elliott Frisch
Elliott Frisch

Reputation: 201447

You can read one line, and then use that to construct another Scanner. Something like,

if (get.hasNextLine()) {
    String line = get.nextLine();
    Scanner lineScanner = new Scanner(line);
    while (lineScanner.hasNextInt()) {          
        elements.add(lineScanner.nextInt());
    }
}

The Scanner(String) constructor (per the Javadoc) constructs a new Scanner that produces values scanned from the specified string.

Upvotes: 1

Related Questions