Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using scanner to read input statement

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

like image 268
Ahmed Nassar Avatar asked Jun 03 '26 01:06

Ahmed Nassar


1 Answers

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()

like image 179
Dan W Avatar answered Jun 05 '26 16:06

Dan W



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!