-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()

Mustapha Belmokhtar
  • 1,231
  • 8
  • 21
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,409
  • 1
  • 20
  • 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,525
  • 3
  • 18
  • 31
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);
  }
 }
}
loadP
  • 404
  • 1
  • 4
  • 15