-1

I want to take the input from a user, in this case, their full name and split it with the .split(" ") command into 2 or 3 sections, depending on number of names, and then print out the results on different lines:

For example,

User inputs:

"John Doe Smith"

Program returns:

John

Doe

Smith

Currently, my code looks like this:

import java.util.Scanner;
public class Task2 {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        String name;
        System.out.println("Enter your full name: ");
        name = input.next();
        String[] parts = name.split(" ");
        System.out.println(java.util.Arrays.toString(parts));

    }
}

This currently only returns the first part of the name.

The program should also be able to deal with someone not having a middle name.

Nawlidge
  • 105
  • 1
  • 2
  • 9

4 Answers4

5

input.next() returns only the first string before the first encountered blank space, try input.nextLine()

мυѕτавєւмo
  • 1,219
  • 7
  • 20
1
import java.util.Scanner;

public class Task2 {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        String name;
        System.out.println("Enter your full name: ");
        while (input.hasNext()) {
            name = input.next();
            String[] parts = name.split(" ");
            System.out.println(java.util.Arrays.toString(parts));
        }
    }
}
tommybee
  • 2,249
  • 1
  • 18
  • 23
0

Check out the JavaDoc of Scanner, the next() method returns the next token of your input stream. Not the entire line.

M. le Rutte
  • 3,447
  • 3
  • 16
  • 30
0

This would also work, maybe.

Executed as e.g. java -jar SplitTest.jar Something Null

public class SplitTest {
 public static void main(String[] args) {
  String name = "";
  for (String arg : args) {
   name = arg;
   System.out.println(name);
  }
 }
}
Tech-IO
  • 386
  • 1
  • 3
  • 14