Please, I want to use the AND operator with checkbox in creating different options.
if (chkd.isSelected()){
lbl.setText("hello");
}
else if (chkd.isSelected() && chkm.isSelected()){
lbl.setText("cool");
}
Please, what's the best approach to do this. I am using Eclipse for Java.
As written, assuming chkd and chkm are defined won't work because if the if statement is true, the else if won't execute.
Try this instead:
if (chkd.isSelected()) {
if (chkm.isSelected()) {
lbl.setText("cool");
} else {
lbl.setText("hello");
}
}
What's happening is we're checking chkd is true, we then check to see if chkm is true we're cool, otherwise, we're hello.
Alternatively you can turn around your if statement.
So checking first for the (a && b) Statement will give you the cool value. If the && is not true, your other Statement (hello) will be displayed.
if (chkd.isSelected() && chkm.isSelected()) {
lbl.setText("cool");
} else if {
lbl.setText("hello");
}
Related
So here's a snippet of code I'm working on:
String direction = s.readLine();
System.out.println(direction);
if (direction.equals("up") != true && direction.equals("down") != true &&
direction.equals("left") != true && direction.equals("right") &&
direction.equals(null) != true) {
System.out.println("Invalid Solution file");
System.exit(0);
}
What it is supposed to do is read a line from a text file (using a BufferedReader) and then if the line isn't either a valid direction or blank then it should print "Invalid Solution" and exit.
The problem is that no matter what the direction string is the if statement still runs. I put in a println to check whether the direction was being read correctly but it seems absolutely fine. So why isn't the code working as intended?
Part of your problem is readability. Fix that and your problem is 90% solved:
private static List<String> DIRECTIONS = Arrays.asList("up", "down", "left", "right");
then
if (!DIRECTIONS.contains(direction)) {
System.out.println("Invalid Solution file");
System.exit(0);
}
The other 10% was how to check for null, which is direction == null, but if you use this code you don't need to, because contains(null) will conveniently return false.
You code is much more complex than it is needs to.
Consider this instead:
Set<String> validDirections = new HashSet<>(Arrays.asList("up", "down", ...
if (validDirections.contain(direction.toLowerCase()) {
// good ...
} else {
// bad ..
}
You can make validDirections a global constant for example; so it could be used in other places as well.
What I am trying to explain here is: your code is low-level. Low level code is hard to write, read, maintain and extend. Programming is always about creating good abstractions. Or vice versa: if you don't use abstractions, you end up with pretty abstract code, like the one you are showing here!
For example: if you need another direction, you have to put into your already way too complicated if condition. In my solution, you just put it into the statement that builds that Set.
Finally: your error message, is saying nothing. So, that string is bad; but why is it? Wouldn't it be better to at least print the string that caused the error?!
Here && direction.equals("right") I think you have done a mistake since it is on contradiction with the rest :
direction.equals("up") != true &&
direction.equals("down") != true &&
direction.equals("left") != true
You test the negation in the most of conditions but direction.equals("right") tests the affirmation.
Try it , it's the same thing but less verbose and more readable :
if (direction !=null && !direction.equals("up") &&
!direction.equals("down") &&
!direction.equals("left") &&
!direction.equals("right") ){
System.out.println("Invalid Solution file");
System.exit(0);
}
First, you should not use != true with a boolean statement, it is bad form. Rewrite like this:
direction !=null &&
!direction.equals("up") &&
!direction.equals("down") &&
!direction.equals("left") &&
!direction.equals("right")
Your error was that you did not include the != true part on one of your statements within the compound if. Replace with the above code to solve the issue.
I'm confused why you are using !=true when your .equals method already returns a boolean. Try this.
String direction = s.readLine();
System.out.println(direction);
if ( direction!=null && !direction.equals("up") && !direction.equals("down")&& !direction.equals("left")&& direction.equals("right")){
System.out.println("Invalid Solution file");
System.exit(0);
}
Try the following code:
boolean match = false;
if (direction.equals("up"))
{ match = true; }
if (direction.equals("down"))
{ match = true; }
if (direction.equals("left"))
{ match = true; }
if (direction.equals("right"))
{ match = true; }
if (direction.equals(null))
{ match = true; }
if (match == false){
System.out.println("Invalid Solution file");
System.exit(0);
}
You might also want to trim the direction string after reading from file.
The quals method returns a boolean so the result does not need to be compared with the true or false value. Also, I would start with null comparison - boolean expressions in Java are shortened so if this part will be fulfilled rest of the expression is not evaluated. The correct expression might look like this:
if (direction == null || (!direction.equals("up") && !direction.equals("down") && !direction.equals("left") && !direction.equals ("right "))) {
}
But this code is not readable. You could use enums or list of Strings like below
List<String> directions = Arrays.asList("up", "down", "left", "right");
String direction = "readValue"
if (!directions.contains(direction)) {
System.out.println("Invalid direction");
System.exit(0)
}
I have a snippet of code that consistently gives me an error:
do {
System.out.println("Choose Role: (Manager, Developer, QA) ");
role = scan.nextLine();
// For testing: ///////////////////////
System.out.println("role is: " + role);
////////////////////////////////////////////////
if (is_numeric(role)) {
System.out.println("Invalid Input.");
continue;
} else if (!role.equalsIgnoreCase("MANAGER") || !role.equalsIgnoreCase("DEVELOPER") || !role.equalsIgnoreCase("QA")) {
System.out.println("Invalid Role");
continue;
} else {
break;
}
} while (true);
I added the "For testing" block just to see, if for some reason there is something happening to the variable role, but its not. No matter how I write manager/developer/qa (whether in caps, small letters, etc) the "Invalid Role" is triggered and the loop goes over again.
Any suggestions?
Logically, this test is wrong
(!role.equalsIgnoreCase("MANAGER") ||
!role.equalsIgnoreCase("DEVELOPER") ||
!role.equalsIgnoreCase("QA"))
Why? Because if the role = "MANAGER", it does not equal "DEVELOPER" (or "QA") and vice-versa. I think you wanted
(!role.equalsIgnoreCase("MANAGER") &&
!role.equalsIgnoreCase("DEVELOPER") &&
!role.equalsIgnoreCase("QA"))
!role.equalsIgnoreCase("MANAGER") || !role.equalsIgnoreCase("DEVELOPER") ||
!role.equalsIgnoreCase("QA")
Is not what you want, replace || with &&.
In your code you're saying: If role is not "MANAGER" OR if role is not "DEVELOPER" OR if role is not "QA".
Due to Short-circuit evaluation, if the first condition is true, the others won't be evaluated because true || anything is always true.
Java if test short circuit for boolean expressions.
Change || to &&
Contrary to what everyone else is saying, if what you're trying to model is "not valid", then don't distribute the negative over each condition and use &&. It's not modelling the right thing. Model "valid", put parentheses around it and negate the whole thing:
if (!(role.equalsIgnoreCase("MANAGER") || role.equalsIgnoreCase("DEVELOPER") ||
role.equalsIgnoreCase("QA"))) {
//...
}
But this is a case where a helper method will improve code clarity greatly. First model what you want to model, not the inverse:
public boolean validRole(String role) {
return role.equalsIgnoreCase("MANAGER") ||
role.equalsIgnoreCase("DEVELOPER") ||
role.equalsIgnoreCase("QA");
}
Then your if statement is hard to get wrong and documents itself:
if (!validRole(role)) {
//...
}
I have this validation to check that user input is not blank and is only letters. If it's blank, it catches it, and if if includes digits it also catches it. If I input the 2 characters it asks for, however, it doesn't go through. I'm not sure how to go about this.
private static boolean isValidSt(String aSt) {
boolean result = false;
try {
if (aSt.length() == 2) {
result = true;
} else if (aSt.length() != 2) {
result = false;
}
for (int i=0; i <aSt.length();){
if (!Character.isLetter(i));{
return false;
}
}
return true;
} catch (NumberFormatException nfex) {
if (aSt == null) System.exit(0);
} catch (Exception ex) {
if (aSt == null) System.exit(0);
}
return result;
}
One problem that I can see right of the bat is this:
if (!Character.isLetter(i));{
return false;
}
That semi-colon after your if does not belong there. After checking your conditional statement, if it was true, it will execute until the semi-colon. The return false; isn't part of the if and will ALWAYS be executed.
As David Wallice rightly pointed out, you also never increment the counter in your for-loop, so were it not the case that the program always returned with false in the first iteration, it would indeed get stuck in an eternal loop. A very commonly used syntax for for-loops would be:
for(int i = 0; i < string.length(); i++) { }
A third and final note from me, this time nothin that would give an error, just good form:
You use System.exit(0); to exit the program as result of an exception. The zero you pass as an argument is usually only used when the program shuts down normally. This is a crash as a result of an error, so I'd use 1 or something.
Well, you could use StringUtils methods, isBlank and isAlpha, for validate what you need
Here is what i want.
If word.length() > 0 then delete or insert word.
So, we can structure the code like this:
if(word.length()>0){
if(action.equals("insert")){
insert(word);
}
else if(action.equals("delete")){
delete(word);
}
}
However, the above nested if is hard to read, so we can do
if(word.length()>0 && action.equals("insert")){
insert(word);
}
else if(word.length()>0 && action.equals("delete")){
delete(word);
}
However, the above code repeats word.length() 2 times which lead to duplicates & that is not good. So if we try
if(word.length()>0){
System.out.println("ok to insert or delete");
}
else if(action.equals("insert")){
insert(word);
}
else if(action.equals("delete")){
delete(word);
}
however, the above code will do the Insert or Delete even if word.length==0.
That quite confusing, cos in wiki http://en.wikipedia.org/wiki/Conditional_(programming), they said:
"Only the statements following the first condition that is found to
be true will be executed. All other statements will be skipped."
if condition1 then
--statements
elseif condition2 then
-- more statements
elseif condition3 then
-- more statements;
...
else
-- other statements;
end if;
What wiki said mean, if condition1 ==true then do the condition2, but if if condition1 ==false then skip all following conditions (condition2,3,...)
But that does not happen in Java?
I am confused??
It will work rewriting your code like:
if(word.length()==0){
System.out.println("word length is 0");
} else if(action.equals("insert")){
insert(word);
} else if(action.equals("delete")){
delete(word);
}
And it is read as: if word length is 0 it will print "word length is 0" otherwise: if action is equals to "insert" it will invoke method insert otherwise if action is equals to "delete" then invoke delete method.
Each if structure has one statement that is executed if the given condition is true. And only this statement is executed, {} could be used to group more statements (block of code). So it is right to say that in a structure of if-elseif only the statements following the first condition that is found to be true will be executed.
The first condition has one block for the true case and one statement (if structure) for the else case. The same for the second condition, and the 3rd has just a block for the true case. Another way to see the statements separations would be:
if(word.length()==0){
System.out.println("word length is 0");
} else
if(action.equals("insert")){
insert(word);
} else
if(action.equals("delete")){
delete(word);
}
using block for the true and false case you would have something like:
if(word.length()==0){
System.out.println("word length is 0");
} else {
if(action.equals("insert")){
insert(word);
} else {
if(action.equals("delete")){
delete(word);
}
}
}
the result is the same.
You misread the wiki. But if you don't like option 1 (which I think is fine) then make the insert and delete methods look at the word length:
public void insert(String word) {
if( word == null || work.isEmpty() ) return
}
Then you have:
if( "insert".equals(action) ){
insert(word);
}
else if( "delete".equals(action) ){
delete(word)
}
I used "insert".equals(action) instead of action.equals("insert") just in case "action" is null.
The wiki is correct, you just have your conditions backwards.
"however, the above code will do the Insert or Delete even if word.length==0."
Not quite. The code will do the insert or delete only if word.length == 0. If word.length > 0, it will print the message, then the insert and delete blocks will be skipped.
It should probably be:
if(word.length() == 0) //if condition1 is true, we will skip all the other blocks after this one
{
System.out.println("Cannot insert or delete");
}
else if(action.equals("insert")) //okay, condition1 must have been false at this point
{
insert(word);
}
else if(action.equals("delete")) //and condition2 must have been false at this point
{
delete(word);
}
if(word.length()>0){
System.out.println("ok to insert or delete");
}
else if(action.equals("insert")){
insert(word);
}
else if(action.equals("delete")){
delete(word);
}
here you do two diffrent checks thats the problem
first you check the word length and then you check for the action
I think the best way you can do it is like you first did it
if(word.length()>0){
if(action.equals("insert")){
insert(word);
}
else if(action.equals("delete")){
delete(word);
}
}
This just is't making sense to me at all.
This is my code:
boolean that = false;
if (that == true);
{
System.out.println("That is " + that);
}
And yet it will print the line even though my output is
That is false
I'm doing this in java and I'm using Eclipse galileo, so each time I compile/run my program it saves it so the compiler should be getting updated version of my program.
What's going on?
A common mistake. Remove the ; at the end of the if statement.
BTW I always write the following if I use brackets and I use the code formatter of the IDE.
if (that == true) {
System.out.println("That is " + that);
}
This means if you have a mis-placed ; or { it can be more obvious.
Remove the ;
boolean that = false;
if (that == true)
{
System.out.println("That is " + that);
}
otherwise the print is always executed.
It's because of the semicolon you have here:
if (that == true);
Remove that semicolon ! It causes the code to do nothing after checking the conditional (that == true) - technically it's an "empty statement" - i.e. we can have a loop like so:
for (int i = 0; ; i++){
System.out.println("Thanks" );
}
And it would go forever!
Try it like this:
boolean that = false;
if (that)
{
System.out.println("That is " + that);
}
Notice the extra semi-colon after the if in your code? That's why.
The logical test is closed by the semi-colon, then the next block is always executed.
If you remove the semi-colon it'll match your intuition.
if (that == true);
// ^ The extra colon you dont need