230k views
5 votes
PRACTICE

.
3. Write a program asks the user to enter their first name and their last name, separated by a space.
Break the input string up into two strings, one containing the first name and one containing the last
name. You can do that by using the indexOf() subroutine to find the position of the space, and then
using substring0 to extract each of the two names. (should save each into its own variable)
• A sample run of the program should look something like this:
Please enter your first name and last name, separated by a space. ?
Mary Smith
Your first name is Mary.
Your last name is Smith.

(I am using Notepad)​

User Fspirit
by
5.4k points

1 Answer

1 vote

class Name

{

public static void main(String args[])

{

String name, firstName,lastName;

int blankIndex,fchar,lchar;

System.out.println("Enter your name having space between first name and last name");

Scanner in = new Scanner(System.in);

name= in.nextLine();

blankIndex = name.indexOf(' ');

firstName = name.substring(0,blankIndex-1);

lastName = name.substring(blankIndex+1, name.length()-1);

fchar = firstName.length();

lchar = lastName.lenght();

System.out.println("You entered the name"+name); Â Â

System.out.println("Your firstname is"+firstName+"has"+fchar+"characters" );

System.out.println("Your lastname is"+lastName+"has"+lchar+"characters" );

}

}

User JJTO
by
5.8k points