Using if-else statement inside Groovy - spock test - java

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

Related

Method that appends to a Stringbuilder based on user entered value

I have a homework problem that wants me to take a phone number and if the phone number has characters to determine what number that is. When I run my current method it returns the numbers but any characters input the method ignores them.
I have tried different versions of my current method.
class Telephone {
String telephoneNumber;
StringBuilder telephone = new StringBuilder();
public String translator(String telephoneNumber){
for(int i=0; i<telephoneNumber.length(); i++){
if(Character.isDigit(telephoneNumber.charAt(i))){
telephone.append(telephoneNumber.charAt(i));
} else if(telephoneNumber.charAt(i) == 'A' || telephoneNumber.charAt(i) == 'B' || telephoneNumber.charAt(i) == 'C') {
telephone.append(2);
} else if(telephoneNumber.charAt(i) == 'D' || telephoneNumber.charAt(i) == 'E' || telephoneNumber.charAt(i) == 'F'){
telephone.append(3);
} else if(telephoneNumber.charAt(i) == 'G' || telephoneNumber.charAt(i) == 'H' || telephoneNumber.charAt(i) == 'I'){
telephone.append(4);
} else if(telephoneNumber.charAt(i) == 'J' || telephoneNumber.charAt(i) == 'K' || telephoneNumber.charAt(i) == 'L'){
telephone.append(5);
} else if(telephoneNumber.charAt(i) == 'M' || telephoneNumber.charAt(i) == 'N' || telephoneNumber.charAt(i) == 'O'){
telephone.append(6);
} else if(telephoneNumber.charAt(i) == 'P' || telephoneNumber.charAt(i) == 'Q' || telephoneNumber.charAt(i) == 'R'){
telephone.append(7);
} else if(telephoneNumber.charAt(i) == 'T' || telephoneNumber.charAt(i) == 'U' || telephoneNumber.charAt(i) == 'V'){
telephone.append(8);
} else if(telephoneNumber.charAt(i) == 'W' || telephoneNumber.charAt(i) == 'X' || telephoneNumber.charAt(i) == 'Y' || telephoneNumber.charAt(i) == 'Z' ){
telephone.append(9);
}
}
return telephone.toString();
}
}
Current results: telephone entered 555555food returns 555555. I would need it to return 555 555 3662
Write a function that takes in two chars, converts them to Strings using String.valueOf() then compare them using equalsIgnoreCase(). And then use that function in all of your else-if conditions. That should make it cleaner.
EDIT
You can also convert the telephoneNumber to upper case (or lower case, your wish) and then proceed as you were as suggested by #Stultuske in the comments

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
}

Why is this causing a constant 'true' in this while loop?

Here is the code;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Do you need instructions for this game? Y/N.");
char a = input.next().charAt(0);
// This while loop always comes out as true.
while (a != 'y' || a != 'n') {
System.out.println("Please enter either Y/N. ");
System.exit(0);
}
if (a == 'y') {
System.out.println("This game is called heads and tails.");
System.out.println("You must type h (heads), or t (tails).");
System.out.println("You will need to keep guessing correctly, each correct guess will increase your score.");
}
}
}
Is there an explanation on why it always comes out as true, and is there an alternative way of doing this? I want to have a validation check, where if the user inputs anything other than y, or n, the program shuts down.
The problem is, when I enter the character, y, or n, it shuts down anyway even though I'm using the != (not equals) operator.
If you have a==y, then a != 'n' is true and a != 'y' || a != 'n' is true.
If you have a==n, then a != 'y' is true and a != 'y' || a != 'n' is true.
If you have a == other thing, a != 'y' || a != 'n' is true.
It is everytime true with the OR operation. Need use AND.
(a != 'y' || a != 'n') at least one of the sub-conditions must be true.
Consider the three possible cases:
a is 'y': false || true gives true
a is 'n': true || false gives true
a is something else: true || true gives true
The character a cannot both be y and n, so the while loop is executed for any input.
Besides, the loop is not looping.
You're checking whether a is not equal to 'y' OR a is not equal to 'n'.
This is always true.
Change it into while ((a != 'y') && (a != 'n')).
The condition inside while in
while (a != 'y' || a != 'n')
is always true because
if a is equal to y, then a is obviously not equal to n. So, result is true.
And again, if a is equal to n, then a is obviously not equal to y. So, result is true.
And again, if a is not equal to y or n, then also the result is true.
So, the condition inside the while is always true. And for this reason, the execution is entering the while loop and after printing your message it is exiting.
So using AND instead of OR may solve your problem, like
while(a != 'y' && a !='n') {
//your work
}
And I think you willing to do this like below,
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Do you need instructions for this game? Y/N: ");
char a = input.next().charAt(0);
while (a != 'y') {
if(a =='n') {
System.exit(0);
}
else{
System.out.println("Please enter either Y/N : ");
a = input.next().charAt(0);
}
}
if (a == 'y') {
System.out.println("This game is called heads and tails.");
System.out.println("You must type h (heads), or t (tails).");
System.out.println("You will need to keep guessing correctly, each correct guess will increase your score.");
}
}
}
Your logic should be "a is not y and a is not n"
while (a != 'y' && a != 'n')

KeyTyped events - Why can I enter a character but when I delete I cannot enter anymore?

I use this code to restrict the input only for numbers, but if the first key I press is a letter, the code let me enter that letter, only one time, then when I erase it I cannot input anymore letters, what is wrong with the code? I want to imput only numbers.
amount.addKeyListener(new KeyAdapter() {
public void keyTyped(KeyEvent e) {
char c = e.getKeyChar();
if (!(Character.isDigit(c)
|| (c == KeyEvent.VK_BACK_SPACE)
|| (c == KeyEvent.VK_DELETE))
|| (amount.getText().length() >= 2)) {
e.consume();
}
}
});
Because of De Morgan's laws:
"not (A or B)" is the same as "(not A) and (not B)".
Your condition is equivalent to:
if ((Character.isDigit(c)
&& c == KeyEvent.VK_BACK_SPACE
&& c == KeyEvent.VK_DELETE))
|| cantBannosTxt.getText().length() >= 2)
When you enter a two letters, the first part of the OR fails but the second one evaluates to true. Since false || true is true, it will consume what you entered.
I'll leave it for you to construct a new validation - Pay attention to the logical && and || when combined with !.

Java if and || issue

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

Categories