Why this code return "Granted" even with different passwords? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Why this code return "Granted" even with different passwords?

class ImportantRoom{ char roomID; int password; String roomCode = (this.roomID + "" + this.password); void open(String userCode){ if(userCode.equals(this.roomCode)){ System.out.println("Granted."); } else { System.out.println("Denied."); } } } class UserCard{ String userName; char userRoom; int password; String userCode = (this.userRoom + "" + this.password); } public class ClosedDoor{ public static void main(String[] args){ ImportantRoom r1 = new ImportantRoom(); r1.roomID = 'b'; r1.password = 4321; UserCard c1 = new UserCard(); c1.userName = "Jonas"; c1.userRoom = 'b'; c1.password = 4322; r1.open(c1.userCode); //The passwords are different but... //the code return "Granted" and I don´t know why... } }

24th Apr 2018, 6:56 PM
srSmith
srSmith - avatar
4 Answers
+ 1
srSmith the moment you use these variables to create the codes, they are still null! You assign the variables values roomID, password, userName and password to the variables roomCode and userCode BEFORE the variables roomID, password, userName and password have got any values. So the result is that roomCode and userCode are both "00". Here is a commented version of your code: https://code.sololearn.com/cI7CSfHs8fIH/#java The more beautiful and corrected code should be: https://code.sololearn.com/c799LyCzWmC7/#java PS: added constructors (with those I can solve this problem very elegant), access modifiers and return methods
25th Apr 2018, 9:25 AM
Johann Leis
Johann Leis - avatar
24th Apr 2018, 8:04 PM
Arun Tomar
Arun Tomar - avatar
+ 2
First you must understand the String class.. in java.. what you write in "---" in java it become object and store in pool area.. after provide the value of roomID. password.. but in object of pool area. the default value is store.. i.e you result is Granted I hope you understand if you not asked me again
24th Apr 2018, 8:06 PM
Arun Tomar
Arun Tomar - avatar
0
I verified the answers and they helped me a lot. I understood that when comparing, the variables were empty or "0". (like i saw in the begining of the course, those are not values but spaces, like containers for the values that will come after.) Thank you all for the help.
25th Apr 2018, 3:53 PM
srSmith
srSmith - avatar