简体   繁体   中英

Splitting a string in Java,

I am trying to split a string into a string array, but when it splits the string only the first part, before the split, is in the array in the [0] slot, but nothing is in [1] or later. This also returns a java exception error when it tries to output spliced[1]

import java.util.Scanner;

public class splittingString
{

    static String s;


    public static void main(String[] args)
    {
        Scanner input = new Scanner(System.in);
        System.out.println("Enter the length and units with a space between them");
        s = input.next();
        String[] spliced = s.split("\\s+");
        System.out.println("You have entered " + spliced[0] + " in the units of" + spliced[1]);
    }

}

You should use: -

input.nextLine()

Currently, you are using next which will return space delimeted

input.next() reads a single word not a whole line(ie will stop at the first space). To read a whole line use input.nextLine() .

Assuming your input is 12 34 , the content of the s variable is 12 , not 12 34 . You should use Scanner.nextLine() to read whole line.

The problems is not with the split() function call. Rather the problem is with the function that you are using to read the input from the console.

next() only reads the first word that you type (basically does not read after the first space it encounters).

Instead use nextLine() . It would read the whole line (including spaces).

Here the corrected code:

import java.util.Scanner;

public class StringSplit {

    static String s;

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out
                .println("Enter the length and units with a space between them");
        s = input.nextLine();
        String[] spliced = s.split("\\s+");
        System.out.println("You have entered " + spliced[0]
                + " in the units of" + spliced[1]);

    }

}

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