I want to read some names from user's input and be able to print each of them on a different line, one after an other, in reverse order. Like the example below : Test Input:
Jane Kate
John
Mary Susan Paul
Boris Ann
Expected Output:
Ann
Boris
Paul
Susan
Mary
John
Kate
Problem :
- I cannot escape from the infinite loop.
- My result should be contained in the "seq" variable but not reachable outside the while loop.
- Last token "Ann" is never past through. What I tried :
- printing at each step.
- forcing the scanner cursor to move forward with .next() method in the loop It looks like the scanner is always waiting for user input.
Here is the code I wrote.
import java.util.Scanner;
class Main {
public String inverse(String first, String second){
return second + System.lineSeparator() + first;
}
public static void main(String[] args) {
Main m = new Main();
Scanner scanner = new Scanner(System.in);
// start coding here
String seq;
seq = scanner.next();
String second;
while (scanner.hasNext()) {
second = scanner.next();
seq = m.inverse(seq, second);
System.out.println(seq);
}
scanner.close();
System.out.println(seq);
}
}
The last printed "seq" in the while loop is almost the result I want, except that it misses Ann. Question : Do you know from where the current behavior is coming from an what do I need to change to have the expected output?
environment details : intellj idea community edition 2021.3.2 connected to a virtual machine with the edu plugin on the hyperskill platform.