0

I need to prompt the user to enter their full name and once they do I need two separate messages to show them your first name is and your last name is. I have everything but what I need to code for the firstName and lastName string. I feel like it has something to do with indexOf? but I can't get it to work correctly.

public class project2b {
    public static void main (String [] args) {
        String firstName;
        String lastName;
        String fullName;

        firstName = 
        lastName =  
        fullName = JOptionPane.showInputDialog(null, "What is your full name?");

        JOptionPane.showMessageDialog(null, " Your first name is " + 
        firstName);

        JOptionPane.showMessageDialog(null, " Your last name is " + 
        lastName);
    }
}
admdrew
  • 3,790
  • 4
  • 27
  • 39
user3247712
  • 37
  • 2
  • 3
  • 8

2 Answers2

1

InputDialog will only return a single String. You need to parse it. String has a handy split() method that will do the parsing for you.

Assuming the user enters their first and last name separated by a space, this will work.

String fullName = JOptionPane.showInputDialog(null, "What is your full name?");

String[] names = fullName.split(" ");
String firstname = names[0];
String lastName = names[1];

My answer does not cover validation. You would normally validate the user's input before using it, but I believe it to be out of the scope of the question.

Rainbolt
  • 3,542
  • 1
  • 20
  • 44
1
String[] names = fullName.split ("\\s");
firstName = names[0];
lastName = names[1];
Predelnik
  • 5,066
  • 2
  • 24
  • 36