Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

}
like image 826
MeryXmas Avatar asked Aug 01 '26 08:08

MeryXmas


1 Answers

You should use: -

input.nextLine()

Currently, you are using next which will return space delimeted

like image 93
chrisw Avatar answered Aug 03 '26 21:08

chrisw



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!