Failed text validation - java

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)) {
//...
}

Related

Java recursion method returns wrong value

I have a bit of a problem with this recursion method. I'm fairly new to Java.
This method checks if an input is either "exit" only or "start" followed by two times either "user" or "easy".
It works fine except for the return. If I enter a wrong input and then a right on it returns the previous wrong input with which I obviously can't continue working, why is that?
I've had this problem before but always somehow managed to avoid it.
You might notice that I print out a valid commadnd right when it's validated, this works fine and produces the result I need. But when printing out the return of the function on line 2 the above mentioned problem takes place. I've added numbers to the printed strings so I can recognize which is which.
I have tried returning immediately when there's a valid command but I still need that retrun at the end since the function gives me an error if return statements are exclusively in conditional statements so the problem persists.
Thanks for any help!
public static void main(String[] args) {
System.out.println(setup() + "3");
}
static String setup() {
System.out.print("Input command: ");
String command = input.nextLine();
String[] split = command.split(" ");
if(!(command.equals("exit") || split.length == 3)) {
System.out.println("Invalid parameters!");
setup();
}
else {
if(command.equals("exit")) {
System.out.println("Valid parameters! Exit");
System.out.println(command + "2");
}
else if(split[0].equals("start") && (split[1].equals("easy") || (split[1].equals("user")) && split[2].equals("easy") || split[2].equals("user"))) {
System.out.println("Valid parameters! Start");
System.out.println(command + "1");
}
else {
System.out.println("Invalid parameters!");
setup();
}
}
return command;
}
first of all I think that you meant to call the recusive call as
return setup()
second of all when using conditional operator (&&, ||) you should use () for make sure you get the logic condition you expect.
if you will update it to :
return setup instead of setup()
validate what you wrap the right part of condition with Parenthesis():
else if (split[0].equals("start") && ((split[1].equals("easy") || split[1].equals("user")) && (split[2].equals("easy") || split[2].equals("user")))) { System.out.println("Valid parameters! Start"); System.out.println(command + "1"); }

Java checkbox with AND operator

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");
}

JAVA Comparing two Strings isn't working

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)
}

Okay, still having trouble with else if method in Java

import java.util.Scanner;
public class SherlockHolmes {
String answer = "Watson";
String response = " ";
int tries = 0;
int tries = 3;
Scanner input = new Scanner(System.in); {
System.out.print("Enter the name of Sherlock's partner, and dear friend.");
response = input.nextLine();
tries++;
if (response.equals("Watson"))
else
while (tries <= 3)
System.out.print("Ooooh, sorry kid! Try again!"); {
System.out.println("Yes, that's right, Barrel Rider.");
break;
} else if (tries == 3) {
System.out.println("Ooooo, sorry kid. But, it looks like you're S.O.L!");
break;
}
}
}
My biggest question is why I'm getting two errors with this method, the error
being: SherlockHolmes.java:16: error: 'else' without 'if'
else
^
SherlockHolmes.java:24: error: 'else' without 'if'
else if(tries == 3)
^
2 errors
I put if code in every line, yet its telling me : "Else without if" for both entries of "else". I am kind of frustrated, and I don't slagging get how Java thinks I have no if when it is clearly there!
What am I doing wrong that Java thinks I have no if code fashioned in?
If you want an if statement with an empty body, you NEED curly braces in Java. Honestly, you should just have way more braces in your code. I strongly suggest reading up on Java coding conventions http://www.oracle.com/technetwork/java/codeconventions-150003.pdf
Example:
if (response.equals("Watson"))
else while (tries <= 3)
For that empty if to compile, you need:
if (response.equals("Watson")) {
}
else while (tries <= 3) {
// loop body
}
You have many syntax errors.
First, you cannot attach an else-if to a while block. Second, if you're trying to make it so that if the response does not equal "Watson", then use the "not equal to" operator, which is simply "!" (an exclamation mark).
Control flow is made up of
if (condition) {} Must be used once, and must be first
else if (condition) {} as many times as you want, optional, must be in between else and if if included
else {} optional, must be last and used once if included
Curly braces and order are mandatory. In Java, it is best practice, and usually required to put curly braces around all blocks: if, while, for. Another thing you need to know is that while loops are not the same as conditionals. They can't be attached to else or else if statements. So your while loop needs to change to
while (tries <= 3) {
...
}
Do this similarly with the conditional statements.
System.out.print("Enter the name of Sherlock's partner, and dear friend.");
response = input.nextLine();
tries++;
while (tries <= 3) {
if (response.equals("Watson")) {
System.out.println("Yes, that's right, Barrel Rider.");
}
else {
System.out.print("Ooooh, sorry kid! Try again!");
break;
}
if (tries == 3) { // If the while loop finishes
System.out.println("Ooooo, sorry kid. But, it looks like you're S.O.L!");
break;
}

How to access JOptionPane commands in showInputDialog?

Here is my code:
public static void nameset(){
int no = 1;
name = JOptionPane.showInputDialog(frame, "The last people who still had cake had to defend it with heir lives, No matter the cost.\nOne of those last people, was you. What is your name?", "",1);
if(name.equals("") || name.equals(JOptionPane.CANCEL_OPTION));{
JOptionPane.showMessageDialog(frame,"Please tell me your name. I don't wanna have to exit out of the game about you.","Hey!",1);
no++;
}if (name.equals("") || name.equals(JOptionPane.CANCEL_OPTION)){
if (no == 2){
JOptionPane.showMessageDialog(frame, "Seriously? Again?! that's it..");
if (name.equals(JOptionPane.CANCEL_OPTION)){
System.exit(0);
}else{
System.exit(0);
}
}
}
}
I want it so if you press the cancel option it tell you to restart. But if you press cancel, it shows an error in the console. I think it's the name.equals(JOptionPane.CANCEL_OPTION), But I'm not sure. Is there any reason for it not to work? Thanks in advance for any help.
The cancel button will always result in null being returned. See official JavaDoc:
Returns: user's input, or null meaning the user canceled the input
So your condition should be changed to:
if(name == null || name.equals(""))
and you also need to remove the semicolon after your first if statement! Otherwise the following block will always be executed.
Once that's fixed, your "exit after 3 times no" will not work because you're not actually looping your input dialog.
Try this
int no = 1;
String name = JOptionPane.showInputDialog(null, "The last people who still had cake had to defend it with heir lives, No matter the cost.\nOne of those last people, was you. What is your name?", "",1);
if(name == null || name.equals(""));{
JOptionPane.showMessageDialog(null,"Please tell me your name. I don't wanna have to exit out of the game about you.","Hey!",1);
no++;
}if (name == null || name.equals("")){
if (no == 2){
JOptionPane.showMessageDialog(null, "Seriously? Again?! that's it.."+name);
if (name == null || name.equals("")){
System.exit(0);
}else{
System.exit(0);
}
}
}

Categories

Resources