Write a Java program named \"NameParser\" which can ask user for his/her full na
ID: 3880935 • Letter: W
Question
Write a Java program named "NameParser" which can ask user for his/her full name, and then parse the name to get first name and last name.
Simulate the following interaction:
Hint:
sc.nextLine() can read in a whole line.
Assume that the user enters full name in "FirstName LastName" format, e.g., if the user enter Alex Johnson, that means Alex is the first name, Johnson is the last name, and the whitespace is the delimiter.
Make use of indexOf() method and .substring() method to extract first name and last name from the full name user entered.
Explanation / Answer
/*The whole answer is well commented so please copy it in your ide and execute, class Name is : NameParser
* Image of your question is not loading properly so my answer is based on text only
* so if you find anything wrong please let me know in comment section
* Solution Approach:
* Solution(1): In this approach you can just use split() method to split the string
* using space as delimiter
* for example: String [] names=fullName.split(" ")
* here split function split(" ") will split your full name into two strings
* which will be stored in names array, the names[0]=FirstName and names[1]=LastName
*
* Solution(2): Based on HINT provided in problem itself
* In this approach first i will find index of space using indexOf method
* after that we can use substring method to find substring
* FirstName will be first substring till white space and last name will be second
* substring after white space
*
* Sample Input: Alex Johnson
* Sample Output:
* Full Name: Alex Johnson
* First Name: Alex
* Last Name: Johnson*/
//Java program to separate first name and last name
import java.util.*;
public class NameParser{
public static void main(String[] args) {
//Instantiating Scanner
Scanner sc=new Scanner(System.in);
//Reading full name
String fullName=sc.nextLine();
//Printing out full name
System.out.println("Full Name: "+fullName);
//Finding the index of first space in name
int indexOfSpace=fullName.indexOf(" ");
//Here we are taking substring from 0 index to white space
String firstName=fullName.substring(0,indexOfSpace);
//Substring from white space to last
String lastName=fullName.substring(indexOfSpace);
//Printing names
System.out.println("First Name: "+firstName);
System.out.println("Last Name: "+lastName);
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.