-1

I want to know how to compare string to a variable. For example I want to check if the input taken is run and if it's not print that is not a command

class Main
{
public static void main(String args[])
{   
System.out.println("a pokrmon appeard");


System.out.println("what would you like to do");
Scanner scan = new Scanner(System.in);
Random genrator = new Random();
String input =scan.nextLine();
int genrate;
 genrate=genrator.nextInt(4);
  String fail ="failed to escape";
   String escaped ="got away safly";
    if  (genrate <= 2){
        System.out.println(escaped);
    }
    else{
      System.out.println(fail);
    }   
    };

I have tried using some methods like if(input=="run") but it doesn't work

Laurel
  • 5,771
  • 12
  • 29
  • 54
cool dude
  • 1
  • 1

1 Answers1

-1

Salam (Hello in Muslim) guy.

To compare a string with another string, you need to call the string1.equals(string2) method.

It compares the value of string1 with string2 and if the values match, it returns true otherwise false.

string1==string2 - compares references to objects of type string, not the values of these objects. You can read more about this here How do I compare strings in Java? . Good luck learning Java. (I'm from Russia, I'm writing from a translator)