Home > Enterprise >  how to comapare an string to a variable
how to comapare an string to a variable

Time:01-22

alright i am new to java i know this is an stupid question but howwww to compare an string to an variable for example i want to check if the input taken is run and if its 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 metheods like 
  if(input=="run") 

but it dosent work

CodePudding user response:

you can't compare string like that as == in java will compare object reference instead of string it self instead try equalsIgnoreCase() which will compare string ignoring the case.

....
if (input.equalsIgnoreCase("run")) {
    // execute case for run
} else {
    // Do something else
}
....

you can read more about string comparision from following link

CodePudding user response:

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)

  •  Tags:  
  • Related