0

So below is my code. I'm trying to use the Scanner class to read an input from the console, and then print out each token on a separate line. But there's a small problem where the user has to input twice. An example of what happens is given below the code

import java.util.Scanner;

public class StringSort {
    public static void main(String args[]) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter a string: ");

        String str = scanner.nextLine();

        int i = 0;
        while (i< str.length()) {
            i++;
            System.out.println("" + scanner.next());
        }
        scanner.close();
    }
}

Example:

Enter a string: 
what is love
what is love
what
is
love
Hai Hoang
  • 974
  • 2
  • 13
  • 30
Sami Jr
  • 33
  • 6

3 Answers3

2

To do what you want use the Scanner class to read an input from the console, and then print out each token on a separate line you can use the String::split method

String str = scanner.nextLine();
String [] arr = str.split (" ");
for (String x : arr) {
    System.out.println (x);
}
Scary Wombat
  • 41,782
  • 5
  • 32
  • 62
0

A more efficient implementation of the above code would be as follows:

    Scanner sc = new Scanner(System.in);

    while (sc.hasNext()) {
        System.out.println(sc.next());
    }

This would avoid use of extra space as done by @ScaryWombat

paradocslover
  • 1,737
  • 1
  • 9
  • 26
0

Scanner should be propertly closed:

try (Scanner sc = new Scanner(System.in)) {
    while (sc.hasNext()) {
        System.out.println(sc.next());
    }
}
oleg.cherednik
  • 12,764
  • 2
  • 17
  • 25