2

i'm writing code to read simple statement of words like "one two three", and put each word into an array String [] token, i wanted to input the statement using Scanner but it only read the first word. when i use the main method to input the statement it works well. can i know what is my mistake?

here are the 2 Codes:

//Using main method:

public class MyLangyage {
    public static void main(String[] args) {
        String statement = "one two three";
        screen(statement);
    }
    public static void screen(String statement) {
        String token[]= statement.split(" ");

        for (int i = 0; i < token.length; i++) {
            System.out.println(token[i]);
        }
    }
}

the result at the console will be:

one two three

//Using The Scanner:

import java.util.Scanner;

public class MyLangyage {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String statement = scanner.next();
        screen(statement);
    }
    public static void screen(String statement) {
        String token[]= statement.split(" ");

        for (int i = 0; i < token.length; i++) {
            System.out.println(token[i]);
        }
    }
}

if i write at console:

one two three

then press enter the result will be:

one

2 Answers 2

7

You are using scanner.next() which gets the next word it reads. If you want to read the whole line and then split use scanner.nextLine()

Sign up to request clarification or add additional context in comments.

Comments

2

Either split a whole input line, or use the Scanner to get one token at a time. Don't do both.

If you want to pull in multiple words from a Scanner, then you'll have to use scanner.next() more than once -- indeed, once per word.

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.