Reputation: 71
I'm new to Java and I'm not sure on how to print the first name and initials when the user inputs their full name. For example, if the user inputs "john doe", it should print out "Greetings, John, your initials are JD"
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.print("Enter full name: ");
String fullName = reader.nextLine();
System.out.print("Greetings, " + getFirstName(fullName) + ", your initials are " + getInitials(fullName));
}
public static String getFirstName(String fullName) {
return fullName.substring(0,1).toUpperCase() + fullName.substring(1).toLowerCase();
}
public static String getInitials(String fullName) {
return fullName.substring(0,1).toUpperCase();
}
}
Thank you for your help and suggestions!
Upvotes: 1
Views: 12603
Reputation: 79035
0
till the first whitespace (i.e. fullName.indexOf(' '))
fullName.lastIndexOf(' ')
).Demo:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.print("Enter full name: ");
String fullName = reader.nextLine();
System.out.print("Greetings, " + getFirstName(fullName) + ", your initials are " + getInitials(fullName));
}
public static String getFirstName(String fullName) {
return fullName.substring(0, fullName.indexOf(' '));
}
public static String getInitials(String fullName) {
int idxLastWhitespace = fullName.lastIndexOf(' ');
return fullName.substring(0, 1) + fullName.substring(idxLastWhitespace + 1, idxLastWhitespace + 2);
}
}
A sample run:
Enter full name: Arvind Kumar Avinash
Greetings, Arvind, your initials are AA
Upvotes: 3
Reputation: 43
What you want to do is break the fullname
into a String array as such.
String[] names = fullName.split("\\s+"); //splits fullname at each space
Then you can use a loop to uppercase each part of the name
for (int i = 0; i < names.length; i++) {
// do your toUpperCasing stuff here
}
Upvotes: 2
Reputation: 344
You can split your string at all blanks and use the first entry of the array as your first name using the method split of String. For the initials you just use all entries of the array.
Upvotes: 2