I'm currently trying to get this part of my code to compare which button the user chooses to the button it self. At the moment it automatically displays the else which is Test2.
Object usersChoice;
Object[] options = { "Go on a journey!", "Exit, i'm tired." };
usersChoice = JOptionPane.showOptionDialog(null, "Hello Melissa :)", "Sunshine program",
JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE,
null, options, options[0]);
if(usersChoice == options )
{
JOptionPane.showMessageDialog(null, "Test1");
} else {
JOptionPane.showMessageDialog(null, "Test2");
}
The problem is with this code (I've moved the declaration of usersChoice for clarity):
Object[] options = [...]
Object usersChoice = JOptionPane.showOptionDialog([...])
The method JOptionPane.showOptionDialog() returns an int. Since that's a primitive, it gets autoboxed to an Integer.
Now you have this code:
if(usersChoice == options )
You are comparing an Object[] to an Object (more specifically, an Integer). That will always be false because they are different types.
Also remember that in Java, using == checks for equality on primitives, but Objects compared this way will be compared by their memory locations. Use .equals() instead to compare Objects.
Related
I currently have 2 checkboxes with an edit text field beside them. There are 4 checkboxes total and I have the logic to check each one and uncheck others if they are checked (almost radio button style). These 2 however could both be checked if they have values in the edit text fields.
However, if the EditText field (which is set to numeric) has a value of 0 or is blank I want it to uncheck the check box and set the value to 0.
Here is the code I have to do this
if (etBase.getText().toString() == "0" || etBase.getText().toString() == ""){
etBase.setText("0");
cbBase.setChecked(false);
} else {
cbBase.setChecked(true);
}
if (etField.getText().toString() == "" || etField.getText().toString() == "0"){
etField.setText("0");
cbField.setChecked(false);
} else {
cbField.setChecked(true);
}
As it sits right now I default the two fields to be "0" when it starts. When this logic runs, it is setting both checkboxes to checked.
I must be missing something here.
To compare string, you must use .equals() function. ( Or .compareTo() but that's no the today's deal)
Ex :
if (etBase.getText().equals("0") || etBase.getText().equals("")){
...
}
var1 == var2 is used to get if these both variable have the same object
I am currently using netbeans GUI drag and drop form, i have a combobox, and i want the combobox value to change based on data received from a database. The other textboxes are receiving their data correcly, the main problem is with the combobox.
String x = tI.getStatus();
if(x == "Assigned"){
cboStatus.setSelectedIndex(0);
}
else if(x == "In progress"){
cboStatus.setSelectedIndex(1);
}
else if (x == "Pending"){
cboStatus.setSelectedIndex(2);
}
else if(x == "Completed"){
cboStatus.setSelectedIndex(3);
}
can anyone tell me how to change the index of the combo box based on data received from database. thanks.
Use String.equals to compare String content. The == operator compares Object references.
if (x.equals("Assigned")) {
You can't compare Strings with ==, use equals()
Use String.equals(). The == operator compares if two Strings reference the same String object; not if they have equal characters in the String.
This question already has answers here:
Why does my if condition not accept an integer in java?
(7 answers)
Closed 3 years ago.
I'm new at Java. I'm looking for some help with homework. I wont post the full code I was doing that originally but I dont think it will help me learn it.
I have a program working with classes. I have a class that will validate a selection and a class that has my setters and getters and a class that the professor coded with the IO for the program (it's an addres book)
I have a statement in my main like this that says
//create new scanner
Scanner ip = new Scanner(System.in);
System.out.println();
int menuNumber = Validator.getInt(ip, "Enter menu number: ", 1, 3);
if (menuNumber = 1)
{
//print address book
}
else if (menuNumber = 2)
{
// get input from user
}
else
{
Exit
}
If you look at my if statement if (menuNumber = 1) I get a red line that tells me I cannot convert an int to boolean. I thought the answer was if (menuNumber.equals(1)) but that also gave me a similar error.
I'm not 100% on what I can do to fix it so I wanted to ask for help. Do I need to convert my entry to a string? Right now my validator looks something like:
if (int < 1)
print "Error entry must be 1, 2 or 3)
else if (int > 3)
print "error entry must 1, 2, or 3)
else
print "invalid entry"
If I convert my main to a string instead of an int wont I have to change this all up as well?
Thanks again for helping me I haven't been diong that great and I want to get a good chunk of the assignment knocked out.
if (menuNumber = 1)
should be
if (menuNumber == 1)
The former assigns the value 1 to menuNumber, the latter tests if menuNumber is equal to 1.
The reason you get cannot convert an int to boolean is that Java expects a boolean in the if(...) construct - but menuNumber is an int. The expression menuNumber == 1 returns a boolean, which is what is needed.
It's a common mix-up in various languages. I think you can set the Java compiler to warn you of other likely cases of this error.
A trick used in some languages is to do the comparison the other way round: (1 == menuNumber) so that if you accidentally type = you will get a compiler error rather than a silent bug.
This is known as a Yoda Condition.
In Java, a similar trick can be used if you are comparing objects using the .equals() method (not ==), and one of them could be null:
if(myString.equals("abc"))
may produce a NullPointerException if myString is null. But:
if("abc".equals(myString))
will cope, and will just return false if myString is null.
I get a red line that tells me I cannot convert an int to boolean.
Thats because = is an assignment operator. What you need to use is == operator.
A single equal sign is assignment: you assign value to a variable this way. use two equal signs (==) for comparison:
if ($menuNumber = 1) {
Update: forgot dollar sign: $menuNumber
I am having som slight difficulties with the following problem.
I have initialized a boolean array called numberArray with 31 indexes. The user is supposed to enter 5 digits between 1 and 30, and each time a digit is entered, the program is supposed to set the proper index to true. For instance, if I enter 5 then:
numberArray[5] = true;
However, if the user enters the value 5 a second time, a message should be given to the user that this number has already been entered, and so the user has to choose a different value. I have tried to create a loop as follows:
public void enterArrayValues() {
for(int i = 1; i < 6; i++) {
System.out.print("Give " + i + ". number: ");
int enteredNumber = input.nextInt();
while (numberArray[enteredNumber] = true) {
System.out.println("This number has already been chosen.");
System.out.print("Give " + i + ". number again: ");
enteredNumber = input.nextInt();
}
numberArray[enteredNumber] = true;
}
}
The problem is that when I run the program, I automatically get the message "The number has already been chosen" no matter what I enter. Even the first time I enter a number. I don't get this. Isn't all the values in the boolean array false by default?
I would greatly appreciate it if someone could help me with this!
while (numberArray[enteredNumber] = true) {
make that
while (numberArray[enteredNumber] == true) {
or change to
while (true == numberArray[enteredNumber]) {
or simply drop the ==true
while (numberArray[enteredNumber]) {
while (numberArray[enteredNumber] = true)
is an assignment, use the == operator or simply while (numberArray[enteredNumber]).
I know its hard to get into while you are still learning, but the earlier you start coding in an IDE the better off you will be. This is one tiny example of something an IDE will warn you about.
Change the while line to:
while (numberArray[enteredNumber]) {
Because mistakenly entering = instead of == is a common mistake, some people always code this type of statement in the following manner:
while (true == numberArray[enteredNumber]) {
With this format, if you use = instead of ==, you will get a compiler error.
Also, if you use a type of static analysis tool such as PMD, I believe you get a warning for the statement that you originally wrote.
Thde problem is in the condition of the while loop - you are using the assignment operator (=), whereas you are supposed to use the equality comparer (==). This way the loop condition is always true, because you are assigning true to the indexed field.
I hope this will work :-) .
The condition in the while loop should be while (numberArray[enteredNumber] == true). You're using the assignment operator =, not the comparison operator ==. Assignment is an expression that returns the assigned value, which is true in your case.
I am using a Bonded JComboBox. What I want to know is how do I check if that JComboBox has any items in it or not.
Thank you.
To test if the JComboxBox reference is null, you can compare it with null using the == operator. To test if the combo-box contains any items, you can use the instance method getItemCount, which returns the number of items it contains.
JComboxBox box = ...
boolean boxIsNull = (box == null); // answers the title of the question
boolean boxHasItems = (box.getItemCount() > 0);