0

I have a portion of code that should do that: 1) Take the name of a color from keyboard 2) Give that color to an object in wich i have another object declaration 3) Decrement from 2 to 1 the correspondant line of the array of 2.

In the main class i want to memorize the color in a variable TemporaryColor.

Scanner input = new Scanner(System.in);
String TemporaryColor = input.nextLine();
playerOrd[1].DecrementoSegnalino(TemporaryColor);

playerOrd is a class that contains this method:

public void DecrementoSegnalino(String color) {
    SegnalinoScommessaGiocatore.decrementaSegnaliniScommessa(color);    
}

SegnalinoScommessaGiocatore have this array:

private int[] numeroSegnaliniScommessa = {2,2,2,2,2,2};

and this method:

public void decrementaSegnaliniScommessa(String color) {
    if (color.equalsIgnoreCase("Black") numeroSegnaliniScommessa[0]--;
    if (color.equalsIgnoreCase("Blue") numeroSegnaliniScommessa[1]--;
    if (color.equalsIgnoreCase("Green") numeroSegnaliniScommessa[2]--;
    if (color.qualsIgnoreCase("Red") numeroSegnaliniScommessa[3]--;
    if (color.equalsIgnoreCase("Yellow") numeroSegnaliniScommessa[4]--;
    if (color.equalsIgnoreCase("White") ) numeroSegnaliniScommessa[5]--;    
    }

There is a problem passing the string that i write with Keyboard... If i use this in the beginning:

playerOrd[1].DecrementoSegnalino("Black");

It works!

What's the problem?

Pittogatto
  • 43
  • 1
  • 9

1 Answers1

1

Don't compare Strings using ==. Use the equals(...) or the equalsIgnoreCase(...) method instead. Understand that == checks if the two objects are the same which is not what you're interested in. The methods on the other hand check if the two Strings have the same characters in the same order, and that's what matters here. So instead of

if (fu == "bar") {
  // do something
}

do,

if ("bar".equals(fu)) {
  // do something
}

or,

if ("bar".equalsIgnoreCase(fu)) {
  // do something
}
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373