Write a Java class that takes a full name (first and last) as inputted by the us
ID: 3671779 • Letter: W
Question
Write a Java class that takes a full name (first and last) as inputted by the user, and outputs the initials. Call the class Initials.
For example, if the name is Jane Doe, the initials outputted will be J and D, and the output should be as follows: J D.
Use of the java.util.Scanner class must be included in this assignment. Note: This class allows the user to provide input to your program after it has begun to run i.e. the input is not provided to the String [] args parameter of your program's main() method, when you first invoke the java command to run it.
Try to include the Scanner method nextline().
Try to include the String method String substring(int beginIndex, int endIndex).
Also try to include the String method int indexOf(String str).
Explanation / Answer
import java.util.Scanner;
class OutputInitial{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String name;
System.out.print("Enter full name: ");
name = sc.nextLine(); // reading full name
sc.close();
int index = name.indexOf(' '); // finding index of space
String firstName = name.substring(0, index);//getting first name from name
String lastName = name.substring(index+1, name.length()); //getting last name
System.out.println(firstName.charAt(0)+" "+lastName.charAt(0));//printing first character of
//firstname nad lastname
}
}
/*
OUTPUT:
Enter full name: Jane Doe
J D
*/
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.