-2

The script below is a test script and I can get the if else to run when the variable is an int. But I can't seem to get it to run the if else statement when a string is entered.

import java.util.Scanner;

public class ifelse
{
   public static void main (String[] args)
   {
      Scanner keyboard = new Scanner (System.in);

      String money;

      System.out.println("Enter how much money you have.");
      money = keyboard.nextLine();

      if (money == "fifty"){

      System.out.println("money");
      }
      else if(money == "seventy"){
      System.out.println("Nothing");
      }
   }
}

The code below works and it's using int for the variable.

import java.util.Scanner;

public class ifelse
{
   public static void main (String[] args)
   {
      Scanner keyboard = new Scanner (System.in);

      int money;

      System.out.println("Enter how much money you have.");
      money = keyboard.nextInt();

      if (money == 50){

      System.out.println("money");
      }
      else if(money == 70){
      System.out.println("Nothing");
      }
   }
}

Any help is appreciated. Thank you!

Matt
  • 79
  • 1
  • 8

1 Answers1

1

You have to compare Strings with .equals function, not with ==.

if(money.equals("fifty")){
 //Code
}
Francisco Romero
  • 12,787
  • 22
  • 92
  • 167