Very new and inexperienced coder, I'm currently working on my first 'from - scratch' project which will be a simple POS (Point Of Sale) restaurant till application.
The till has an admin panel which allows the user to change the menu presets and prices and will require a password to access it.
I am sloppy and using a lot imports as I am as I said very new.
Please take a look at the following:
if (source == passwordSubmit){
if (logInPassword.getText() == adminPassword){
loginFrame.setVisible(false);
adminFrame.setVisible(true);
}
else logInPassword.append("Incorrect");
}
That code is within my ActionListener handler which lets the user enter text into the JTextArea called logInPassword and it compares the user text with the adminPassword preset string (currently set to Password as default)
But my code doesn't quite work... It's active as it gives me an "Incorrect" append into the logInPassword JTextArea but I'm typing in the correct password.
Do I need a getter or something?
Not sure what I'm missing.
use .equals()
if (source == passwordSubmit){
if (logInPassword.getText().equals(adminPassword){
loginFrame.setVisible(false);
adminFrame.setVisible(true);
}
else logInPassword.append("Incorrect");
}
When you use the == operator in Java, you are just comparing shallow reference values. The line source == passwordSubmit would work (since both should refer to the same object). However with strings, it is possible to have two string objects that equal the same in value. In that case, you have to do logInPassword.getText().equals(adminPassword) instead of logInPassword.getText() == adminPassword. The equals method compares by value of the strings.
Related
I've read through several questions/answers with similar sounding issues but I've not found a solution to my issue and have been racking my brain over this for the last few hours so here goes.
On the web form I'm writing tests for, there are several drop down lists and if the option "Don't know" is selected from any of them, a check box will be displayed and needs to be selected or the form cannot be submitted.
I'm storing the selected values as Strings and then have the clicking of the check box within an IF statement checking whether any of those drop down values is "Dont know" (the actual value in the drop down is recorded as "Dont know"):
String drpdwn_WAN = driver.findElement(By.id("idontknow4")).getAttribute("value");
String drpdwn_SFTPAuthMethod = driver.findElement(By.id("idontknow5")).getAttribute("value");
String drpdwn_SFTPCreds = driver.findElement(By.id("idontknow6")).getAttribute("value");
String drpdwn_Bandwidth = driver.findElement(By.id("idontknow7")).getAttribute("value");
String drpdwn_Data = driver.findElement(By.id("idontknow8")).getAttribute("value");
//click on the Understood check box (only appears when 'Don't know' option is selected)
if(drpdwn_WAN == "Dont know" || drpdwn_SFTPAuthMethod == "Dont know" || drpdwn_SFTPCreds == "Dont know" || drpdwn_Bandwidth == "Dont know" || drpdwn_Data == "Dont know"){
driver.findElement(By.name("understand")).click();
}
I've run through the code in debug mode and have confirmed that the drop down values are being correctly stored but even when at least one of the drop down values is "Dont know" it will not run the code within the IF statement and instead just ignore it.
I've written my test so that the options selected from the drop downs are randomised so need a lot of conditional logic to verify other elements on the page such as the check box. As such the above is only one example of the types of IF/ELSE statement I have in my code but it seems that all code contained within any IF/ELSE statements is not getting executed and is instead being ignored and passed over. Can anyone explain to me what it is that I'm doing wrong here and why the IF statements are seemingly not being executed?
This is the first time I've posted on here so apologies if any of the information is lacking or not clear. Also apologies if the solution to this is rather simple but I'm new to the world of Java development.
Thanks in advance for any help offered!
Having read stackoverflow.com/questions/513832/ it appears that I should have been using .equals() instead of == for string comparisons. Code worked as expected once I replaced == with .equals()
if(drpdwn_WAN.equals("Dont know") || drpdwn_SFTPAuthMethod.equals("Dont know") || drpdwn_SFTPCreds.equals("Dont know") || drpdwn_Bandwidth.equals("Dont know") || drpdwn_Data.equals("Dont know")){
driver.findElement(By.name("understand")).click();
}
.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();
}
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);
}
i have two textfield and one JComboboxes the problem is i want the program to check if the textfields have "admins" typed in it and administrator selected in JCombobox if so the the program will show a messagebox to the user.
Your code in your comment:
if (btn1 == y.getSource() && tf1.toString() == "admin" &&
tf2.toString() == "admin" && c1.getSelectedIndex() == 0 )
shows you using == to compare Strings, and also trying to get text from a JTextField using toString(), neither of these is good. Instead for String comparison, use the equals(...) or equalsIgnoreCase(...) methods, not == since the latter checks to see if two objects are identical which is not what we're generally interested. We don't care if one String is held by a different object as another but rather that the two Strings have the same chars in the same order, which is what the two equals methods do.
Next, use the getText() method to extract the text held by your JTextField. For example:
if (btn1 == y.getSource() && tf1.getText().equals("admin") &&
tf2.getText().equals("admin") && c1.getSelectedIndex() == 0 )
Also, please show code as an edit to your question, not in a comment since it doesn't format well as a comment. Finally, if my advice doesn't help, consider showing us more code and giving more detailed information on the problem with this code.
I met a small problem when running a Java class that I wrote, though the design is pretty straightforward. I've created a JPanel, and I've added four JTextFields onto it and I've attached a button to this JPanel, too. Then, I've associated an ActionListener to this button being pressed. The code is like:
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
if (imageIdField.getText() == "" &&
captionField.getText() == "" &&
creditField.getText() == "" &&
titleField.getText()== "")
{
mediaXML = "";
results.clear();
results.put("error1", "more");
}
else
{ ....
}
}
The strange thing is after I've pressed the OK button, and I did input text in those four JTextFields, still it will fall in the IF branch as if I didn't input any text in any of these four fields.
I've been debugging this for a while, but no clue. Could anyone give me some hint like whether .getText() == "" is a valid way for testing no input?
Thanks in advance!
As has been mentioned, using == is not correct. For readability, try:
field.getText().isEmpty()
or
field.getText().trim().isEmpty()
Generally a bad idea to use == on Strings, or most other things. It checks that the objects are exactly the same instance, not that they have the same value. "" != new String("").
field.getText().equals("")
Or possibly better:
field.getText().isEmpty()
Use getText().equals("") instead of ==
Use == to check if it is the same object in memory, and .equals("YOUR STRING") to check if the content of the object is the same.
You should use .equals. Also, you might want to do something like this:
imageField.getText().trim().length() == 0 //The same for the others
or
imageField.getText().trim().isEmpty() //The same for the others
if you want to make sure that the user has actually written some characters instead of just white spaces.
== only checks whether the left hand side and the right hand side refer to the exact same instance of an object. And since "" translates to something like new String(""), it will always return false, if you compare it with a string that already exists.
If you want to compare whether two instances of a class have the same state you need to use equals(). In your case *.getText().equals(""). A more elegant method would to use the isEmpty() method of the String class.