Reputation: 45
I have to creat an application that prompts the user for his or her name, including title. The application should display "Hello,sir" if the string stars with Mr., "Hello,ma'am" if the string starts with Ms.,Mrs., or Miss, and "Hello,name" otherwise where name is the user's name.
This is what I have so far, the application chokes when the user types in Mrs, because it finds the Mr s first, and I'm having trouble figuring out what I could do to get it to work. Let me know, thank you all beforehand for your answers! Beginner Java so keep it simple please!
package chapter6java;
import java.util.Scanner;
import java.lang.String;
public class FormalGreeting {
public static void main (String [] args) {
String name, mr = "Mr", mrs = "Mrs", ms = "Ms", miss = "Miss";
Scanner input = new Scanner(System.in);
System.out.print("Enter your name including title (ie. Mr, Mrs): ");
name = input.nextLine();
if (name.startsWith(mr)) {
System.out.println("Hello,sir");
} else if (name.startsWith(mrs)) {
System.out.println("Hello,ma'am");
} else if (name.startsWith(ms)) {
System.out.println("Hello,ma'am");
} else if (name.startsWith(miss)) {
System.out.println("Hello,ma'am");
} else {
System.out.println("Hello," +name);
}
}
}
Upvotes: 0
Views: 707
Reputation: 4727
String.split("\\.");
If your string has a dot, it will be splitted. Then you can compare to "Mrs" and "Mr."
Or you can split with a space (and remove the dot of the end of string if there is one)
Upvotes: 1
Reputation: 51
Try to swap the 'mr' and 'mrs' if else
if (name.startsWith(mrs)) {
System.out.println("Hello,ma'am");
} else if (name.startsWith(mr)) {
System.out.println("Hello,sir");
}else ......
Upvotes: 0
Reputation: 11817
Change your comparison to first compare for mrs
:
if (name.startsWith(mrs)) {
System.out.println("Hello,ma'am");
}else if (name.startsWith(ms)) {
System.out.println("Hello,ma'am");
}else if (name.startsWith(miss)) {
System.out.println("Hello,ma'am");
}else if (name.startsWith(mr)) {
System.out.println("Hello,sir");
}else{
System.out.println("Hello," +name);
}
Explanation:
In your solution, the program flow will enter the first if
branch (ie, the branch where name starts with mr
). Since mrs
also starts with mr
, you need to change the order of comparison to compare the mrs
before mr
Upvotes: 0