-1

The follow are my java code

i want to enter: asd 123456 hellohello

output:

asd

123456

hellohello

However it come out error. anyone can help me?

package test;

import java.util.Scanner;
public class test1 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        Scanner sc = new Scanner (System.in);
        String cs = sc.next();

        String[] output = cs.split("\\s+");
        System.out.println(output[0]);
        System.out.println(output[1]);
        System.out.println(output[2]);
    }
}
Laurel
  • 5,965
  • 14
  • 31
  • 57
T Lam
  • 13
  • 3

3 Answers3

2

There are a couple of things that I have fixed with your code:

import java.util.Scanner;
public class SplitStringWithSpace {
    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        String cs = sc.nextLine();
        //close the open resource for memory efficiency
        sc.close();
        System.out.println(cs);

        String[] output = cs.split("\\s+");
        for (String retval : output) {
            System.out.println(retval);
        }
    }
}
  • Use the enhanced for loop so you dont have to manually navigate the array.
  • Close the resource after you have used it.
Mukul Tripathi
  • 275
  • 1
  • 2
  • 10
0

next() only returns next token in the input not the entire line , your code will throw ArrayIndexOutOfBoundsException as it stands bcoz output has length equal to 1.

you need nextLine() method to get the entire line.

Ramanlfc
  • 8,283
  • 1
  • 18
  • 24
0

Here sc.next() uses spaces delimiter. So given the input as foo bar, you get:

sc.next(); //`foo`
sc.next(); //`bar`

Either you may go for sc.nextLint() and use rest of the code as it is. If you have to continue with sc.next(), you may try this code snippet.

while(sc.hasNext()) { //run until user press enter key
  System.out.println(sc.next());
}