-2
package chapter6;
import java.util.Scanner;

public class formal_greeting {

    public static void main(String[] args) {
        String title;
        String name;
        String mr = null;
        String miss = null;
        String ms = null;
        String mrs = null;

        Scanner input = new Scanner(System.in);
        System.out.print("Enter your name: ");
        name = input.next();
        System.out.print("Enter your title: ");
        title = input.next();

        if (title.equalsIgnoreCase(mr)) {
             System.out.println("Hello sir");
             }else if (title.equalsIgnoreCase(miss)) {
             System.out.println("Hello ma'am");
             }else if (title.equalsIgnoreCase(ms)) {
             System.out.println("Hello ma'am");
             }else if (title.equalsIgnoreCase(mrs)) {
             System.out.println("Hello ma'am");
             }else {
             System.out.println("Hello " + name);
             }



    }

}

I can't figure out why my if statements won't work. so far it only displays (Hello "name") can someone please tell me what is wrong with my if statement???

Chase
  • 39
  • 7

2 Answers2

0

Problem is not in the if statements.Change your method input.next() to input.nextLine() .Because using next() you will get only what you entered before the space. But if you use nextLine() the Scanner will read the entire input line.
For more reference click here.
Hope this helps

Community
  • 1
  • 1
Rahal Kanishka
  • 676
  • 10
  • 26
0

You need to know the difference between a String variable and a string literal.

In your code, mr is a string variable. The value that it stores is null as you can see from this line:

String mr = null;

In the if statement, you test whether the user input is equal to the value string variable. Let's say you entered "Mr" in the console:

User input    Value of the mr variable
"Mr"          null

Are they the same? No.

The same goes for all the if statements. Finally the execution comes to the else and executes the stuff there since every if statement failed.

What you need to do is to use a string literal instead of a string variable.

A string literal is denoted by double quotes:

"This is a string literal"

So your if statements would look like:

if (title.equalsIgnoreCase("mr")) {
/*                         ⬆︎ ⬆︎
                          Quotes here!
*/

Alternatively, you can use variables as well. But you should not give them a value of null. Instead, give them a string literal:

String mr = "mr";
// etc.

This way, you don't need to change your if statement.

Sweeper
  • 145,870
  • 17
  • 129
  • 225