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
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With