MeryXmas
MeryXmas

Reputation: 63

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]);
    }

}

Upvotes: 2

Views: 609

Answers (4)

Ankit
Ankit

Reputation: 6980

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]);

    }

}

Upvotes: 3

Crozin
Crozin

Reputation: 44376

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.

Upvotes: 3

Ivaylo Strandjev
Ivaylo Strandjev

Reputation: 70929

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

Upvotes: 5

ed_me
ed_me

Reputation: 3508

You should use: -

input.nextLine()

Currently, you are using next which will return space delimeted

Upvotes: 11

Related Questions