+ 1

How to make IF statement to compare string corectly?

When i making “if” statement like: If (yourAge>=18 && yourName==“Tomas”) { System.out.println(“Welcome”); } else { System.out.println(“access denied”); } I’m getting that access denied all the time even if i put correct answer for welcome condition

5th May 2018, 11:38 PM
Tomáš Beránek
Tomáš Beránek - avatar
4 Respostas
+ 7
The equals method doesn't support boolean operators inside them, you have to do separately In your code the "if" statement doesn't stop the code if it's condition is true, so what happens is that after testing the "if (yourAge<=18)" the code keeps running to the next "if" statement. The more simple solution is to nest "else if" and "else" statements. Here is an example with everything that I said: https://code.sololearn.com/chhXk9s5tn7B/?ref=app
6th May 2018, 10:03 AM
Leonardo Matheus
Leonardo Matheus - avatar
+ 6
When you use the "==" you compare the location in memory, this does not work on strings. In strings use "equals()" to compare two words. Example: yourName.equals("Tomas").
5th May 2018, 11:46 PM
Leonardo Matheus
Leonardo Matheus - avatar
0
Works like magic..thanks a lot
6th May 2018, 6:54 AM
Tomáš Beránek
Tomáš Beránek - avatar
0
I have 2 other problems: don´t know how to add more conditions for names... like: if (yourName.equals("Tomas"||"Adam"||"John") And if i write code like this: String yourName; int yourAge; System.out.println("Hello type your name please"); Scanner UserInput = new Scanner(System.in); yourName = UserInput.nextLine(); System.out.println("Hello, your name is: "+yourName); System.out.println("what is your age?"); UserInput = new Scanner(System.in); yourAge = UserInput.nextInt(); if (yourAge<=18) { System.out.println("Access denied"); } if(yourAge>18 && yourName.equals("Tom")) { System.out.println("Welcome"); } else { System.out.println("You are not welcome"); } it add "else" answer even if want only the "access denied" when i put in age like 15..
6th May 2018, 8:20 AM
Tomáš Beránek
Tomáš Beránek - avatar