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
2
  • 5
    what do you think + scanner.next()); does? Commented Dec 12, 2018 at 1:40
  • Please fix your indentation and clarify your question, what did you expect? Commented Dec 12, 2018 at 1:42

3 Answers 3

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);
}
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

0

Scanner should be propertly closed:

try (Scanner sc = new Scanner(System.in)) {
    while (sc.hasNext()) {
        System.out.println(sc.next());
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.