I have a series of four yes/no choices in four separate dialog boxes, the cumulative results of which will lead to one of twelve separate links (e.g., Yes/Yes/Yes/No -> link A, Yes/No/No/Yes -> link B, etc). The branching logic uses boolean values.
Here's what I have so far...just the first dialog box and printing the results for validation.
public class OutageGuideSelector{
public static void main(String[] args){
boolean contactServerUp;
boolean vistaUp;
boolean stormOutage;
boolean vistaCSUp;
//
int contactServerEntry = JOptionPane.showConfirmDialog(null,
"Is the contact server up", "Please select",
JOptionPane.YES_NO_OPTION);
System.out.println("result from entry " + contactServerEntry);
if(contactServerEntry==1)
contactServerUp = true;
else
if(contactServerEntry==0)
contactServerUp = false;
/* System.out.println(contactServerUp); */
}}
Right now, the results of clicking YES reults in a 0 being returned, NO results in a 1. Is this normal, seems counterintuitive, and there's nothing at docs.oracle.java that shows a clear example of the output values except this which seems to suggest that the public static final int YES_NO_OPTION default in 0.
Additionally, the line System.out.println(contactServerUp); comes back with an error that the field contactServerUp might not have been initialized when I un-comment it, so I can't see if my convert-int-to-boolean is working.
First: It appears that JOptionPane method does not include any boolean returns...except getWantsInput() which returns the value of the wantsInput property...so I assume I'm already being the most efficient I can with this. I'd like to know if there's an easier way.
Second, what am I missing that prevents my console output statement from recognizing the contactServerUp? Where's my misplaced semicolon?
According to the javadoc, when one of the showXxxDialog methods returns an integer, the possible values are:
YES_OPTION
NO_OPTION
CANCEL_OPTION
OK_OPTION
CLOSED_OPTION
You should test against those constants:
contactServerUp = (contactServerEntry == JOptionPane.YES_OPTION);
The value returned by the the JOptionPane dialogs are values defined as constant fields in the class.
Although, indeed, one could assume that 0 means false and 1 means true, the values are more ids for the different buttons a dialog can have.
To know if the user pressed yes or no, you can compare the return value to the constant fields described here. For example, in your case :
contactServerUp = (contactServerEntry == JOptionPane.YES_OPTION);
Since a dialog a JOptionPane can have more than two possible 'answers' a boolean would be a poor representation. You are forgetting about the YES, NO and CANCEL option, or what about just a OK answer.
If it would have been written today, I suspect a Enum would have been used instead of an int.
As for the second question, the compiler does not allow access to uninitialized variables.
When you do the following, there is a chance that the variable might not be initialized:
if(contactServerEntry==1)
contactServerUp = true;
else
if(contactServerEntry==0)
contactServerUp = false;
What if, for example, contactServerEntry == JOptionPane.CLOSED_OPTION? In that case, your boolean value is never initialized.
You need to add an else clause at the end of your if-else chain, or initialize contactServerUp value to a default value in the beginning.
Related
I am using the following method to generate an ID number. It starts with the number 0, and compares it to the ID numbers of all existing objects in an array, if it does not equal any of the objects then it should return that ID number and break out of the loop. If it does equal any of the objects it will + 1 and compare 1 to the ID numbers of all objects, until it finds a number that does not match/ is not in use.
However when I run the program, the for loop loops indefinitely, despite being controlled by a boolean which is triggered when all object IDs have been compared and non match. Here is the code:
public int GenerateProductID(){
Boolean NewIDFound = false;
Boolean inUse = false;
int potentialID;
for(potentialID=0;NewIDFound==false;potentialID++){
for(Product productToCompare: this.Products){
if (potentialID==productToCompare.getID()){
{inUse=true;}
}
}
if(inUse!=true){
NewIDFound=true;
return potentialID;
}
}
return potentialID;//Had to return something here although the function will never get here.
}
I have spent a while trying to get to the bottom of this, Java is a new endeavour so apologies in advance if something obvious has been missed. Any help on how to fix this would be greatly appreciated.
inUse means "the current potentialID is in use"; as such, it needs to be reset for each new potentialID.
In my quiz game on the very end of a level I have to check some conditions, 4 of them. During the game I add +1 to an integer variable, 4 variables. On the end of the level I sum these values to another integer, activeButtonsTotal. And I set 4 boolean values to true or false. So, I need to check 2 conditions four times: if it's my boolean is false AND if my activeButtonsTotal is equal to 16 and if it is to set one of my buttons to Enabled, and this same thing for the next boolean and activeButtonsTotal, and 4 times like this. I need to go through all 4 of them. I tried with if statements, and else if but no luck.
boolean columnACorrecct, columnBCorrect, columnCCorrect, columnDCorrect;
activeButtonsTotal = activeButtonsA+activeButtonsB+activeButtonsC+activeButtonsD;
if((columnACorrect=false) && (activeButtonsTotal==16)){
columnA.setEnabled(true);
}
if((columnBCorrect=false) && (activeButtonsTotal==16)){
columnB.setEnabled(true);
}
if((columnCCorrect=false) && (activeButtonsTotal==16)){
columnC.setEnabled(true);
}
if((columnDCorrect=false) && (activeButtonsTotal==16)){
columnD.setEnabled(true);
}
im not sure that i follow all your logic, but your "if" statements all are missing an equal sign. You said you have to compare if your boolean is false, AND the number, but you are assigning "False" inside the condition. you need "==".
I would do:
if(activeButtonsTotal==16)
{
columnA.setEnabled(!columnACorrect);
columnB.setEnabled(!columnBCorrect);
columnC.setEnabled(!columnCCorrect);
columnD.setEnabled(!columnDCorrect);
}
I would do something like that:
columnA.setEnabled(!columnACorrect && activeButtonsTotal==16);
columnB.setEnabled(!columnBCorrect && activeButtonsTotal==16);
columnC.setEnabled(!columnCCorrect && activeButtonsTotal==16);
columnD.setEnabled(!columnDCorrect && activeButtonsTotal==16);
You are assigning your boolean variable to false every time you try to check a condition.
This will result in the condition to be false and will never run the code within the block.
To check for equality, use ==;
columnACorrect==false
columnBCorrect==false
columnCCorrect==false
columnDCorrect==false
But I would recommend using:
!columnACorrect
!columnBCorrect
!columnCCorrect
!columnDCorrect
It does the same thing. The 2nd option is more preferable.
I am looking for advice on basic designs for a system with this functionality.
Let's say I have a data class like this:
Class nodeData
boolean aValue;
boolean bValue;
boolean cValue;
Using some set of business logic, I define mutually exclusive sets of titles to the node that this data represents.
For example, I define this title:
Singular.YES means Only one of aValue, bValue, cValue is true
Singular.NO means 0 or more than 1 of aValue, bValue, cValue is true
or this one:
aDefined.YES means aValue is true.
aDefined.NO means aValue is false.
or this one:
totalTrue:.0 means 0 of the values are true
totalTrue.1 means 1 of the values are true
etc.
In each of these cases, the titles are mutually exclusive among each other in that same set, and which title within a set applies to that data is based on some hard-coded business logic.
Then, each specific title is associated with some specific piece of functionality. For example, I might say that "If aDefined.YES, call methodX" or "If totalTrue.0, call methodX and then methodY".
If N is the number of title sets, then there are N! combinations of titles, and N! combinations of associated functionality. How do I accomplish: For each node data, find the set of titles associated with that data. Run the functionality associated with each of those titles.
EDIT: This isn't a boolean logic question, this is a design question. My point is that I want a robust method of associating data sets with some name or subclass given arbitrary business logic.
skipping the Value parts
I think this should help you but your question is a bit vague.
//checking if one of the 3 bools are true
if((a&&!b&&!c)||(!a&&b&&!c)||(!a&&!b&&c))
Singular = Singular.YES
else
Singular = Singular.NO
//checking if one bool is true
if(a)
aDefined = aDefined.YES
else
aDefined = aDefined.NO
//checking how many bools are true
int i = 0;
if(a)
i++;
if(b)
i++;
if(c)
i++;
TotalTrue = i;
I am building a calculator (gas law calculator) which has four text fields, and I need three fields to be filled by numbers to calculate the fourth value. The equation is v1/p1 = v2/p2. But the problem is I don't know which three values the user will fill. So I need to find an algorithm to check each text field and determine which is empty. I am using swing classes. Jut give me direction.
Thank you!
DocumentListener
to try to avoiding KeyListener
possible way could be FocusListener also, notice Focus is asynchronous
Well, what do you expect the value of the "empty" field to be?
Of course it will be the empty string, "".
So just test for which fields contents equal the empty string (or have a length of 0).
How about this?
private boolean validateField(JComponent component)
{
if (component.getText().trim().length() == 0){
return false;
}
else{
return true;
}
}
If you want to check if JTextField is empty you just do it as follows:
Example(sudo code):
-> JTextField field = new JTextField("v1:");
-> if(field.getText().isEmpty == true){...}
else{...}
I am trying to take the values from the text fields below to use with parent.addNewRoom(roomNo,roomEnSuite); but roomEnSuite is a Boolean value in the parent class. What is the correct procedure to get a Boolean from a JTextField?
public void actionPerformed( ActionEvent ae)
{
String item = ae.getActionCommand();
if ( item.equals("Confirm"))
{
String roomNo = nameJTextField.getText();
String roomEnSuiteS = idJTextField.getText();
parent.addNewRoom(roomNo,roomEnSuite);
this.dispose();
}
else if ( item.equals("Cancel"))
{
parent.resetButtons();
this.dispose();
}
}
To give a full answer from my above comments:
Handling boolean input using a JTextField would not be a good way to go about things as there are many variations the user could type yes/no/true/false, etc. mispelling?
Using a JRadioButton (for single answers) or JCheckbox (for multiple answers) would be a better way to go about handling true or false input. I would suggest a JRadioButton as you wouldn't want the user checking true and false.
http://docs.oracle.com/javase/tutorial/uiswing/components/button.html
Assuming the user entered the string true or false, you can turn it into a boolean with:
boolean value = Boolean.parseBoolean(idJTextField.getText());
A JTextField is meant to provide Strings. So unless you want the user to type true or false in the textfield (or whatever string you will parse to a boolean), there are better options available
a JCheckBox, which is typically used for toggle settings, like true-false
JRadioButtons (one for each setting, so two in this case)
And here a link to the corresponding Swing tutorial with examples on how to use these buttons
But if you really want to got with a textfield, then you should get the text from it and parse it by using for example Boolean.valueOf
As long as the value entered is always going to be true or false you can get a Boolean using;
boolean value = Boolean.parseBoolean(enSuiteJTextField.getText());