.containsAll will work but .equals is not working.
You are adding the numbers everytime. You should use local variables or local initialization. Else your passcode list gets 5 more numbers everytime you call your function.
Because you said "a security keypad", I have to say ignore what anyone else says that is technically correct, you are doing it wrong. By storing the passcode in a "plain" format, you might as well just leave a sticky note on the keypad with the passcode on it.
What you should be doing is hashing the input and the passcode and comparing the hashed versions. And don't use hashCode(), that function is unreliable for this purpose. (Example of how to hash)
Also, according to the Java Docs, equals is the correct way to check. You are miss-handling your list instances. You should step through the debugger to see everywhere in your code that you do something that alters your global variables.
I think you have a problem where you are comparing your arrays. Have a look at this SO question: equals vs Arrays.equals in Java
if (digitList.size() == 5 && digitList.equals(passcode)) { // are the arrays the same array?
guideArea.setText("Correct Password.");
digitList.clear();
}
what it should be:
if (digitList.size() == 5 && Arrays.equals(digitList, passcode)) { // are the two arrays CONTENT the same
guideArea.setText("Correct Password.");
digitList.clear();
}
Related
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 3 years ago.
So I am having an issue, I put my self to the test of creating a 2D sandbox game kind of for fun, but has turned out evolving into something a bit more after about a week, but, to the point, I am saving chunk data into a few files, these are just .file or, just the most basic file type I assume, and the problem persists even using .txt files.
So what's happening is after saving a file containing the object name, x, and y positions, I am creating an object in a linked list using that information, when I enter a new "chunk", but things are not exactly right, somehow, my images load up for the tiles correctly, which is handled in the constructor for that tile, being called after it is added to the list, however, what made me notice is I have a check in the tiles update method, to see if it wants to change to a different grass texture, and it doesn't happen, so I did some checking and printing, and well, I can tell that the name variable certainly contains the desired name, eg. "dirt", however it does not equal "dirt", so I thought it was catching some spaces and I even trimmed the String, and when I run a test like
if(name == "dirt")System.out.print("dirt is actually "+name);
else System.out.print("dirt is apparently not "+name);
and the result is always, "dirt is apparently not dirt", with no spaces, and even when looking in the actual file I save it to, it saves the name fine, I have them saving in an order like so;
name x y
eg.
dirt 0 560
dirt 28 560
and so on, these all load in position perfectly fine and what stumps me is that the initial image loads in correctly, which is quite explicit, a switch statement to determine what the image, material type and such should be..
I was wondering if anyone has come across something like this and what it could possibly be.
Also any code desired I will add to the desc.
(I didn't know so many people would be so quick to help. Thank you all, I know it was a simple problem, but it had me super confused, now thanks to you all I understand something about comparing variables and objects I should have really known before, and which is really important
.)
Chances are the result is "dirt" but you're not testing it correctly.
Test should be if name.equals("dirt") ... not the equality operator ==.
See: How do I compare strings in Java?
Equality in Java:
String dirt1 = "dirt";
String dirt2 = new String("dirt");
System.out.println(dirt1 == "dirt"); // TRUE
System.out.println(dirt1 == dirt2); // FALSE
System.out.println(dirt1 == dirt2.intern()); // TRUE
System.out.println(dirt1.equals(dirt2)); // TRUE
I am doing a lab for college where I have to compare Moneybags. initially I instantiate them and add money etc. etc.I already have MoneyBag mb0, and mb1,but now I have to compare them with this code...it cannot be changed.
mb0.compare(mb1);
The class is MoneyBag. I need to return "Is Less Than","Is equal to", or "is Greater Than."
I currently have:
public int compare(MoneyBag mb1){
}
However, I cannot access mb0. I can access the int value of mb1. I need to compare them, print out the string literals, and obviously return the String. How would I do that? The top code cannot be changed, I have to make the second code work from it.
Regardless of the language, you should be able to access mb0 using something like in the body of your compare function.
return this.value - mb1.value;
Values of 0 represent "equal", values greater than 0 mean "Greater Than" and values less than 0 mean "Less Than";
Good luck
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
I was working on my game I am making, when I came across an error. My if/else if statement skips right to the else if statement, even if it shouldn't.
String neededCredits = "200";
if(Peeamnt.getText() == neededCredits) {
System.out.println("You can afford this");
JOptionPane.showMessageDialog(BuyPoopButton,
"You have unlocked the Poop Button for 200 Pee Credits!",
"Toilet Master",
JOptionPane.WARNING_MESSAGE);
}
else if((!(Peeamnt.getText() == neededCredits))) {
System.out.println("You cannot afford this");
JOptionPane.showMessageDialog(BuyPoopButton,
"You do not have enough Credits to buy this!\n"
+ "To buy it, you need 200 Pee Credits!",
"Toilet Master",
JOptionPane.ERROR_MESSAGE);
}
Even if the text of Peeamnt is an even 200, the code will jump to the else if statement, telling me that I don't have 200 Pee Credits. (The game I am making included a lot of toilet humor.) Anyway, if anyone sees the error I have in this code, please let me know. Let me know if you need more code.
With a Java String object, the == operator doesn't compare the string value.
Try changing the first if comparison to:
if(Peeamnt.getText().equals(neededCredits)) {
You will need to do something similar for the else if as well.
Strings are objects. Objects have a reference. Two String objects containing the same sequence of characters may not be the same object, thus having different references. The == operator (generally) checks for reference equality.
To compare the character sequence of two String objects for equality, you have the equals method. So use Peeamnt.getText().equals(neededCredits) instead.
String is an Object. Comparing Object, you have to use equals to judge whether the Object content is same. Using == is to compare Object reference
Use equals method to compare String object, because == operator means you compare object base on memory address. Always remember to never use == to compare objects in Java.
Try to use equals method if the getText() returns a string don 't use == sign. I suppose that getText() returns aString` object.
FYI: Double equal sign is used to see if two Objects are the same
and TO check if the objects has the same value equals() method should be used. Note: The objects that You compare with equals() should override it otherwise the results are corrupted, and the last thing when You overridesequals() method remember to override hashCode() too.
Use method equals to compare String object, because == operator means you compare object base on memory address.
* never use == to compare object.
String neededCredits = "200";
if(neededCredits.equals(Peeamnt.getText()) {//compare following you never see, because nullPointerException "neededCredits" always has value :-)
System.out.println("You can afford this");
JOptionPane.showMessageDialog(BuyPoopButton,
"You have unlocked the Poop Button for 200 Pee Credits!",
"Toilet Master",
JOptionPane.WARNING_MESSAGE);
}
else if((!(neededCredits.equals(Peeamnt.getText()))) {
System.out.println("You cannot afford this");
JOptionPane.showMessageDialog(BuyPoopButton,
"You do not have enough Credits to buy this!\n"
+ "To buy it, you need 200 Pee Credits!",
"Toilet Master",
JOptionPane.ERROR_MESSAGE);
}
This question already has answers here:
Which is better/more efficient: check for bad values or catch Exceptions in Java
(11 answers)
Closed 9 years ago.
I have seen two styles for checking whether a variable is a valid integer in Java. One by doing an Integer.parseInt and catching any resulting exception. Another one is by using Pattern.
Which of the following is better approach?
String countStr;
int count;
try {
count = Integer.parseInt(countStr);
} catch (Exception e) {
//return as the variable is not a proper integer.
return;
}
or
String integerRegex = "([0-9]{0,9})";
if (countStr.isEmpty() || !Pattern.matches(integerRegex, countStr)) {
//return as the variable is not a proper integer.
return;
}
My question here is, is doing an Integer.parseInt() and catching an exception for validation a standard way to validate an int? I admit that my regex is not perfect. But is there any built-in methods available in Java for validation of int? Actually isn't it better to do some validation instead of simply catching the exception?
Using the approach above is better as it considers all types of possible errors and handles all cases. For instance what you have written will not parse negative numbers correctly.
It only makes sense to write your own verifier if you want to validate a given subset of all integers.
A general advice: don't re-invent the wheel unless you have strong reasons to do so.
There's a really good reason to not go with the second approach if you actually want to check if the given string can be represented as a 32bit integer and not just that it represents an integer in the mathematical sense.
I'm sure we all agree that 2147483648 (2**31 for those paying attention) is a perfectly fine integer, but it's only one of infinitely many numbers for which the two options will give different results. So if you want to check if you can represent a string as a 32bit integer use the parseInt method, if you just want to see if it's an integer go with the regex.
PS: That said don't catch Exception, but the correct NumberFormat exception instead..
These two function serve different purposes. If you just want to make sure that the string cotains a particular pattern, then use the second approach. If you need to convert it, then you should can parseInt() In this case it wouldn't make sense to check it and convert it as well.
However, if you have specific requirements for the number, then you may have to check it first regardless, because parseInt() may not always throw an exception if it can parse something which still doesn't fit your requirement.
If you just validat an Integer, I think the second way is better.
These two methods both will work fine, but obviously different focus. The former focuses on the transformation itself, while the latter is clearly more attention checked. And you want to check a number is, so I think the second method is better. Also, I think, some of the second method more readable, allowing code maintenance is a clear to see, where the logic is in checking the validity of a number instead of a string into a number.
I've got a problem that I'm rather confused about. I have the following lines of code in my android application:
System.out.println(CurrentNode.getNodeName().toString());
if (CurrentNode.getNodeName().toString() == "start") {
System.out.println("Yes it does!");
} else {
System.out.println("No it doesnt");
}
When I look at the output of the first println statement it shows up in LogCat as "start" (without the quotes obviously). But then when the if statement executes it goes to the else statement and prints "No it doesn't".
I wondered if the name of the node might have some kind of non-printing character in it, so I've checked the length of the string coming from getNodeName() and it is 5 characters long, as you would expect.
Has anyone got any idea what's going on here?
Use String's equals method to compare Strings. The == operator will just compare object references.
if ( CurrentNode.getNodeName().toString().equals("start") ) {
...
Use CurrentNode.getNodeName().toString().equals("start").
In Java, one of the most common mistakes newcomers meet is using == to compare Strings. You have to remember, == compares the object identity (Think memory addresses), not the content.
You need to use .equals
if ("start".equals(CurrentNode.getNodeName().toString()) { ... }