0

This code is supposed to get a letter input from the user and then assign a value to the letter based on how many points it's worth. This is my first part working in Java, and for some reason I can't get the if statement to assign the variable anything.

import java.util.Scanner;

public class LetterValues {

public static void main(String args[]){

    Scanner scanner = new Scanner(System.in);
    String letterInput1, letterInput2, letterInput3, letterInput4;
    int firstLetter = 0, secondLetter = 0, thirdLetter = 0, fourthLetter = 0;

    // Asks for first input letter
    System.out.print("What is your first letter?  ");

    // Reads the first input letter
    letterInput1 = scanner.next();

    // Converts the first letter to upper case, prints out to check
    System.out.println(letterInput1.toUpperCase());

    // Prints out first letter to check
    System.out.println(letterInput1);

    // Assigns a value to the firstLetter int based on the value of letterInput1
    if ( (letterInput1 == "A") || (letterInput1 == "E") )
    {
        firstLetter = 1;
    }
    else if ( (letterInput1 == "D") || (letterInput1 == "R") )
    {
        firstLetter = 2;
    }
    else if ( (letterInput1 == "B") || (letterInput1 == "M") )
    {
        firstLetter = 3;
    }
    else if ( (letterInput1 == "V") || (letterInput1 == "Y") )
    {
        firstLetter = 4;
    }
    else if ( (letterInput1 == "J") || (letterInput1 == "X") )
    {
        firstLetter = 8;
    }
    else
    {
        System.out.println("Error.");
    }

    System.out.println(firstLetter);
    }
}

The result is:

    What is your first letter?  A //<--input
    A
    A
    Error.
    0
    What is your second letter? 

2 Answers2

2

Use equals() to compare Strings:

"A".equals(letterInput1)
BobTheBuilder
  • 18,858
  • 6
  • 40
  • 61
1

Use equals() instead of == for comparing Strings

Reason

equals() method is present in the java.lang.Object class and it is expected to check for the equivalence of the state of objects!. That means, the contents of the objects. Whereas the == operator is expected to check the actual object instances are same or not.

Example

Consider two different reference variables str1 and str2

str1 = new String("abc");
str2 = new String("abc");

if you use the equals()

System.out.println((str1.equals(str2))?"TRUE":"FALSE");

You will get the output as TRUE

if you use ==

 System.out.println((str1==str2)?"TRUE":"FALSE");

Now you will get the FALSE as output because both str1 and str2 are pointing to two different objects even though both of them share the same string content. It is because of new String() everytime a new object is created.

Rakesh KR
  • 6,357
  • 5
  • 40
  • 55