简体   繁体   中英

Split method is splitting into single String

I have a little problem: I have a program that split a String by whitespace (only single ws), but when I assign that value to the String array, it has only one object inside. (I can print only '0' index). Here is the code:

public void mainLoop() {
        Scanner sc = new Scanner(System.in);

        String parse = "#start";

        while (!parse.equals("#stop") || !parse.isEmpty()) {
            parse = sc.next();

            String[] line = parse.split("[ ]");
            System.out.println(line[0]);
        }
}

The 'mainLoop' is called from instance by method 'main'.

By default Scanner#next delimits input using a whitespace. You can use nextLine to read from the Scanner without using this delimiter pattern

parse = sc.nextLine();

The previous points mentioned in the comments are still valid

while (!parse.equals("#stop") && !parse.isEmpty()) {
    parse = sc.nextLine();

    String[] line = parse.split("\\s");
    System.out.println(Arrays.toString(line));
}

When you call next on scanner it returns next token from input. For instance if user will write text

foo bar

first call of next will return "foo" and next call of next will return "bar" .

Maybe consider using nextLine instead of next if you want to get string in form "foo bar" (entire line).


Also you don't have to place space in [] so instead of split("[ ]") you can use split(" ") or use character class \\s which represents whitespaces split("\\\\s") .


Another problem you seem to have is

while( !condition1 || !condition2 )

If you wanted to say that loop should continue until either of conditions is fulfilled then you should write them in form

while( !(condition1 || condition2) )

or using De Morgan's laws

while( !condition1 && !condition2 )

如果要按单个空格分割,为什么不这样做?

String[] line = parse.split(" "); 

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