简体   繁体   中英

Why does this not print multiple times?

I am trying to translate text to piglatin here is the code so far.

import java.util.*;

public class Start {

    static Scanner in = new Scanner(System.in);

    public static void main(String args[]){

        String input;

        System.out.println("What is your phrase?");
        input = in.next();
        convert(input);


    }//end main

    public static void convert(String in){

        String out;
        String[] inArry = in.split(" ");

        for(int i = 0; i < inArry.length; i++){

            System.out.println(inArry[i]);

        }


    }//end convert

}

If I type in the console "Hello world" it only prints Hello. I have no clue why.

The next() method in the Scanner returns the next token, tokenized by a delimieter which is by default whitespace.

A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. The resulting tokens may then be converted into values of different types using the various next methods.

So input is only "Hello" .

Use the nextLine() method to get the whole line instead.

input = in.nextLine();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM