Java if and || issue - java

I'm doing this little program, but unfortunately I ran into this issue..
if (ccnString.charAt(0) != '4' || ccnString.charAt(0) != '3') {
System.out.println("The String entered does not fit any of the Credit card standards");
System.exit(0);
}
My program does not recognize if I put in any of the integers in my String.
However, if I delete my || and the last part, the if statement recognizes the first integer.
What am I missing here?

if (ccnString.charAt(0) != '4' || ccnString.charAt(0) != '3')
Is always true.
Every character is != '4' or != '3'
I guess you want && instead.
Details:
The statement A || B is true if A is true or B is true (or both are true).
In your example, lets say that the first character is '4'.
A = ccnString.charAt(0) != '4' is false (4 != 4 is false)
B = ccnString.charAt(0) != '3' is true (3 != 4 is true)
So A || B is true because B is true.

This is an addition to the many other answers that correctly state that you must use and (&&) instead of or (||).
You have been fooled by De Morgan's laws. They define how boolean expressions are negated.
In your example, the original expression that defines a valid user input is as follows:
validInput = userPressed3 or userPressed4
But as we are interested in invalid user input, this expression has to be negated:
not(validInput) = not(userPressed3 or userPressed4)
According to De Morgan, not(A or B) is equal to not(A) and not(B). So we can also write:
not(validInput) = not(userPressed3) and not(userPressed4)
In other words: It's De Morgan's fault! ;)

You probably want
if (ccnString.charAt(0) != '4' && ccnString.charAt(0) != '3') {
System.out.println("The String entered does not fit any of the Credit card standards");
System.exit(0);
}
This would give your error message only for Strings that don't start with 4 AND don't start with 3.
Your original condition gives an error for any String that either doesn't start with 4 OR doesn't start with 3, and since all Strings satisfy that condition, you'll always get your error message.
If you require additional conditions after the initial test, you can do :
if (ccnString.charAt(0) != '4' && ccnString.charAt(0) != '3') {
System.out.println("The String entered does not fit any of the Credit card standards");
System.exit(0);
} else if (ccnString.charAt(0) == '3' && ccnString.charAt(1) == '7') {
// here you know that ccnString starts with 37
} else if (...) {
...
}
... add as many else ifs as you need ...
else {
// default behavior if all previous conditions are false
}

It should be && not ||
ccnString.charAt(0) != '4' && ccnString.charAt(0) != '3'
Else (ccnString.charAt(0) != '4' || ccnString.charAt(0) != '3' always true

if ((ccnString.charAt(0) != '4' && ccnString.charAt(0) != '3')
|| (ccnString.charAt(0) == '3' && ccnString.charAt(1) == '7')) {
System.out.println("The String entered does not fit any of the Credit card standards");
System.exit(0);
}

Related

Rules not obeyed by if statement

The below code is supposed to tell the user whether his input is a vowel or consonant or digit less than 1. The program however returns "Vowel" for all capital letters including consonants and whenever a digit is entered "Consonant" is returned. Ex - if a is entered, result = vowel. If b, result = Consonant. If B, result = Vowel (should be Consonant). If 1, result = Consonant(should be Digit) . Any advice would be greatly appreciated. Thanks.
package checkVowelorConstantorNumber;
import java.util.Scanner;
public class Main {
public static void main (String [] args) {
Scanner inp = new Scanner (System.in);
boolean tf = false;
while(tf == false) {
System.out.println("Enter a character which is a - z or A - Z or
less than 1");
char cha = inp.next().charAt(0);
inp.nextLine();
if(Character.isLetter(cha) && cha == 'a'||cha == 'e' || cha == 'i' || cha == 'o' || cha == 'u' || Character.isUpperCase(cha)) {
System.out.println("Vowel");
}
else if(Character.isLetter(cha) && cha != 'a'|| cha != 'e' || cha != 'i' || cha != 'o' || cha != 'u' || Character.isUpperCase(cha)) {
System.out.println("Consonant");
}
else if(Character.isDigit(cha) && cha <= 1 ) {
System.out.println("Digit");
}
else System.out.println("Invalid character");
}
}
}
Your if statement first checks if the given character is a letter and not an a, 1 is neither so that is false, then it checks if 1 is not equal to 'e' causing that statement to be true, thus printing 'Consonant'. You have to make the check for isLetter for every comparison. Therefore i would recommend something like this:
if(Character.isLetter(cha)) {
// Check for vowel or consonant based on letters
} else if(Character.isDigit(cha) && cha <= '1') {
System.out.println("Digit");
} else {
System.out.println("Invalid character");
}
You also should make the if statement for consonant use && instead of ||, since it should be none of the specified chars.
Pay close attention to logical ands (&&), logical ors (||) and parentheses. Consider the following, modified from your code with some comments.
char cha = inp.next().charAt(0);
inp.nextLine();
if (cha.isLetter()) {
// convert to uppercase to simplify the if
char uc = cha.toUpperCase();
if (uc == 'A' || uc == 'E' || uc == 'I' || uc == 'O' || uc == 'U') {
// it's a vowel
} else {
// it's a letter that isn't a vowel (consonant)
}
} else {
// it's not a letter
if (cha.isDigit() && cha < '1') {
// but it is a digit less than 1
} else {
// it's something else (digit not less than '1' or not a digit)
}
}

While loop just not working

I am just wanting some explanation (why) on why the following code is not working and a solution(How) to make the code run.
The goal of the program is to get a user input of a playing card, either J,Q,K,A, lower case or upper case. The program must only accept one of these values so it needs to validate the user input, displaying when its wrong and prompting till an accepted value is entered. The program then must take that user entered value and print the name of the playing card onto the console, Jack, Queen, King, Ace.
package practical_1;
import static java.lang.System.out;
import java.util.Scanner;
public class Question_4 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String Usr_Card;
out.print("Enter Card Letter Here.... ");
Usr_Card = input.next();
Usr_Card = Usr_Card.toUpperCase();
while (Usr_Card != "K" || Usr_Card != "Q" || Usr_Card != "J" || Usr_Card != "A"){
out.print("Invalid Input\nEnter Valid Card Letter Here: ");
Usr_Card = input.next();
Usr_Card = Usr_Card.toUpperCase();
}
switch (Usr_Card) {
case ("J"):
out.print("Jack");
break;
case ("Q"):
out.print("Queen");
break;
case ("K"):
out.print("King");
break;
case ("A"):
out.print("Ace");
break;
}
}
}
The OR operator || returns true if any section is true. In your example, if card is not K or not Q or not J or not A, continue the loop.
Let's break that down. User enters a "K"
Usr_Card != "K" // false
Usr_Card != "Q" // true
Usr_Card != "J" // true
Usr_Card != "A" // true
false || true || true || true === true // continue the loop
What we really want to check is whether the input is invalid. The input is invalid when it does not match at least one of K, Q, J, or A. Or better stated, when not K AND not Q and not J and not A.
We simply change our conditions from || to &&. Same example
Usr_Card != "K" // false
Usr_Card != "Q" // true
Usr_Card != "J" // true
Usr_Card != "A" // true
false && true && true && true === false // do not continue the loop
while (Usr_Card != "K" && Usr_Card != "Q" && Usr_Card != "J" && Usr_Card != "A")
Let's try an invalid example. Use enters an "A"
Usr_Card != "K" // true
Usr_Card != "Q" // true
Usr_Card != "J" // true
Usr_Card != "A" // true
true && true && true && true === true // continue the loop
So as you can see, we only continue the loop when we don't match any of the valid characters thanks to our AND && operation.
And as Scary Wombat has pointed out, you should not use == or != with strings. You should use .equals
while( !Usr_Card.equals("K") && !Usr_Card.equals("Q") && !Usr_Card.equals("J") && !Usr_Card.equals("A") )
This expression,
(Usr_Card != "K" || Usr_Card != "Q" || Usr_Card != "J" || Usr_Card != "A")
always evaluates to true, therefore the loop with never exit.
You need AND logic here, like:
(Usr_Card != "K" && Usr_Card != "Q" && Usr_Card != "J" && Usr_Card != "A")
Change the condition in the while loop to:
while (Usr_Card.equals("K") && Usr_Card.equals("Q") && Usr_Card.equal("J") && Usr_Card.equals("A"))
EDIT: As pointed out by #ScaryWombat in the comments, method of string comparison changed from '!=' to equals().

Using || OR Operator within If Statements alongside characters

I'm very new to programming in general, and I'm having a bit of trouble with a program I'm writing in Java to help calculate my final grade in a class. This part of the program asks me what letter grade I would like to receive, and then determines if that input is valid. For example, if I typed into the keyboard that I wanted to receive a letter grade of "Z", because that is not a valid grade, I would like my program to output "Invalid Input" and exit. The code I have written below is not producing any syntax errors, but it outputs "Invalid Input" for every letter grade I choose, even A, B, and C (inputs that should be valid). Any help in understanding what's wrong is more than welcome.
Scanner input = new Scanner(System.in);
char desiredGrade
System.out.print("What letter grade do you want to achieve for the course? ");
desiredGrade = input.next().charAt(0);
if (desiredGrade != 'A' || desiredGrade != 'B' || desiredGrade != 'C'){
System.out.println("Invalid Input");
System.exit(0);
}
In addition to this, it would be helpful to not have to worry about case sensitivity with the inputs. I know I can use .ignoreCase() or .equalsIgnoreCase() with strings, but I'm not quite sure how to implement that with char.
see this Answer
For Upper- and Lowercase you can wrap your char in Character and then call toLowerCase and check the input and the expected value on Lowercase.
In your example
desiredGrade != 'A' || desiredGrade != 'B' || desiredGrade != 'C'
If you want to use the || operator you have to do it like that
if(!(desiredGrade == 'A' || desiredGrade == 'B' || desiredGrade == 'C')){
}
That way you check if the Input is A, B, or C and if not then exit
Lets say desiredGrade = 'A'
if (desiredGrade != 'A' || desiredGrade != 'B' || desiredGrade != 'C'){
The first condition will be false, but the second and third will be true. So
if (false || true || true)
Will result always in true.
The way to do it is using operator AND &&
if (desiredGrade != 'A' && desiredGrade != 'B' && desiredGrade != 'C'){
This way, if the user decides to input 'A' the operation will be
if (false && true && true){
Resulting in false. And if the user inputs 'Z', the operation will be
if (true && true && true){
That will result true and execute the Invalid input output.
EDIT
As it has been mentioned. The user may input 'a' (lowercase) for which condition desiredGrade = 'A' will be false since 'a' != 'A' (is not equal).
So it will be wise to convert desiredGrade to uppercase before the if statement.
Try out
(desiredGrade != 'A' && desiredGrade != 'B' && desiredGrade != 'C')
Basically, you want to check if desiredGrade is different than A and different than B and different than C, print out invalid input.
Try this:
if (! Arrays.asList ('A', 'B', 'C').contains (Character.toUpperCase (desiredGrade))) {
// your error handling
}

Using if-else statement inside Groovy - spock test

Currently when I use if else in a Groovy - spock when:, only the if is executed and the else is not. Is there any other way of implementing if-else inside spock tests? I tried switch case and encountered the same.
if (value == 'x' || 'y' || 'z') {
//execute below info
} else if (value == 'a') {
//execute below info
}
Due to the groovy truth 'y' is treated as boolean true, that's why else is not executed.
Probably you tried to evaluate this:
if (value == 'x' || value == 'y' || value == 'y') {
//execute below info
} else if (value == 'z'){
//execute below info
}
But also you can try to modify the if-expression to:
if (value in ['x', 'y', 'y']) {...}
I am not sure if I have to make this a comment or an answer.
Your code under the else block is not executing because value == 'x' || 'y' || 'y' is always true because the character literal 'y' is always evaluated to true.
Non-empty Strings, GStrings and CharSequences are coerced to true.
Try this: if (value == 'x' || value == 'y' )

Why does `if (guess != 'a' || guess != 'A' || ...)` not work? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
Here is my code, I know the if statement is really long and the code could probably be more efficient, but I just want to know the answer to this as it is driving me nuts.
while (whileloop == 1)
{
if (guess != 'a' || guess != 'A' || guess != 'b' || guess != 'B' || guess != 'c' || guess != 'C' || guess != 'd' || guess != 'D' || guess != 'e' || guess != 'E' || guess != 'f' || guess != 'F' || guess != 'g' || guess != 'G' || guess != 'h' || guess != 'H' || guess != 'i' || guess != 'I' || guess != 'j' || guess != 'J' || guess != 'k' || guess != 'K' || guess != 'l' || guess != 'L' || guess != 'm' || guess != 'M' || guess != 'n' || guess != 'N' || guess != 'o' || guess != 'O' ||guess != 'p' || guess != 'P' || guess != 'q' || guess != 'Q' || guess != 'r' || guess != 'R' || guess != 's' || guess != 'S' || guess != 't' || guess != 'T' || guess == ' ')
{
System.out.println ("\nNot a Point. Try again.");
guess = IBIO.inputChar ("If the missile is launched from Point B, which Point will the missile hit? ");
}
else
whileloop = 2;
}
Because you wanted a logical and && (not a logical or ||). When you use || if any condition is true (such as the letter A not being the letter B, the entire expression is true). You could use an || with two ands. Something like
if (!(guess >= 'a' && guess <= 'z') || !(guess >= 'A' && guess <= 'Z'))

Categories