Groovy switch not behaving as expected - groovy

I've got the test.groovy script below, but when I run it, I get the following output.
groovy test.groovy
set color to good
set color to unstable
unstable
Why am I seeing 'set color to good'?
Line 13 states
case "SUCCESS" :
But buildStatus is "UNSTABLE"
I've never used a switch statement before in groovy, so could be missing something pretty basic.
test.groovy
def print_arg(def arg){
buildStatus = "UNSTABLE"
previousBuild = "FAILURE"
// println "$arg"
switch(buildStatus) {
case { it != "SUCCESS" } :
switch(previousBuild) {
case "SUCCESS" :
println "set color to danger"
color = 'danger'
break;
}
case "SUCCESS" :
switch(previousBuild) {
case { it != "SUCCESS"} :
println "set color to good"
color = 'good'
break;
}
case "UNSTABLE" :
println "set color to unstable"
color = 'unstable'
break;
}
println "$color"
}
print_arg()

You see set color to good because you don't have a break statement at the end of your 1st case.
The 1st case matches with { it != "SUCCESS" }, the nested switch does not. Then the excecution proceeds to the 2nd case due to the lack of break before. The 2nd case executes and also doesn't have a break, so it falls through to the 3rd case.
So, the switch operates exactly how it supposed to.
I'm not sure what your original intention was and having nested switch ops does not increase the readability of your code, but I'd put your code like that:
switch(buildStatus) {
case { it != "SUCCESS" } :
switch(previousBuild) {
case "SUCCESS" :
println "set color to danger"
color = 'danger'
break;
}
break // << ADD THIS
case "SUCCESS" :
switch(previousBuild) {
case { it != "SUCCESS"} :
println "set color to good"
color = 'good'
break;
}
break // << ADD THIS
case "UNSTABLE" :
println "set color to unstable"
color = 'unstable'
break;
}

Related

Java - Default Switch Statement

I am writing some tests for a Java method which contains a switch statements but it seems that the "default statement" does not work. I only accept: Yes, No, Maybe. Everything else should return Maybe. My test always return the user input, does not matter what the user typed, so I guess my switch statement is not correct.
I have tried to move the default statement on the top
#Override
public String choice(String ans) {
getChoice = ans;
switch (ans) {
case "Yes":
break;
case "No":
break;
default:
getChoice = "Maybe";
}
return getChoice;
}
Thank you!
Your switch should work... As Kyle tells you "what are you overriding ?"
But why a switch when you can perform an "if then else" ?
Public String choice (String choice) {
If (choice.equals("yes") || choice.equals("no") {
return choice;
else {
return "maybe";
}
}
Switch is fine for multiple choices

a groovy switch case statement with several variables

Is it possible to have a switch-case statement with more than a variable in groovy? I tried with tuples but the case part doesn't accept more than one argument.
I am trying to avoid several nested if statements so instead of
if (a==1) {
if (b==2) {
if (c==3) {
// do something
}
}
}
else {
if (a==4) {
if (b==5) {
if (c==6) {
//do something else
}
}
}
}
Can I do:
switch(a,b,c) {
case : (1,2,3) // if a==1, b==2 and c==3
// do something
...
case : (4,5,6)
// do something else
...
}
}
Groovy is just dirty java, you don't need any class definition. everything you write in a java method you can write it directly in groovy.
switch (num) {
case 1:
case 2:
case 3:
System.out.println("1 through 3");
break;
case 6:
case 7:
case 8:
System.out.println("6 through 8");
break;
}
To answer your question, inside the switch we need an expression, not function parameters.
Based on your edit, I believe that this should work:
if (a == 1 && b == 2 && c == 3) {
// do something
} else if (a == 4 && b == 5 && c == 6) {
// do something else
}
If you want a switch statement instead, that's possible:
def val = [a, b, c]
switch (val) {
case {it == [1, 2, 3]}:
// something
break;
case {it == [4, 5, 6]}:
// something else
break;
class Solution{
static void main (String...args){
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in))
def val=br.readLine()
switch(val){
case('E0'):
println "Basic"
break;
default:
break;
case('E1'):
println "Inter"
break;
case('E2'):
println "Advance"
break;
default:
println "not defined"
}
}
}

JAVA Switches, if then else and booleans with string

I'm having a bit of trouble getting a few parts of my code to work properly.
I'm still a bit new to java and could some direction and clues to where I went wrong.
The error comes from the if statements. I feel like i know why they are erring out because the || are undefined but I'm not sure how to fix it. What I'm trying to get it to do is take the inputs either L,R,F,B (left, right, forward and back). lowercase the input and either accept either one or the other using boolean "or".
import java.util.Scanner;
public class ChooseYourAdventure {
public static void main(String[]args) {
Scanner input = new Scanner(System.in);
System.out.print("Choose a diection: ");
String direction = input.nextLine().toLowerCase();
System.out.printf(" %s and %s/n",getDirection (way),getYourChoice (found));
}
public static String getYourChoice (String found) {
String result = "Unknown";
switch (found)
{
case "l":
result = " now we all know you can turn left unlike Zoolander";
break;
case "left":
result = " now we all know you can turn left unlike Zoolander";
break;
case "r":
result = " you fall down a hole never to be seen again... sad.";
break;
case "right":
result = " you fall down a hole never to be seen again... sad.";
break;
case "f":
result = " YOU ARE THE KWISATZ HADERACH!!";
break;
case "forward":
result = " YOU ARE THE KWISATZ HADERACH!!";
break;
case "b":
result = " you are a scaredy cat but, you live to fight or runaway another day";
break;
case "back":
result = " you are a scaredy cat but, you live to fight or runaway another day";
break;
}
return result;
}
public static String getDirection(String way) {
String result;
if (way == "l" || "left") {
System.out.print("Your character moves left");
}
else if (way == "r" || "right") {
System.out.println("You character moves right");
}
else if (way == "f" || "forward") {
System.out.println("Your character moves forward");
}
else if (way == "b" || "back") {
System.out.println("Your character moves forward");
}
else {
System.out.println(" You cant go that way ");
}
return result;
}
}
All your if statements are wrong. When using || or &&, you need to specify the variable way on each side of the ||:
if (way == "l" || way == "left") {
System.out.print("Your character moves left");
}

How to compare for null in groovy correctly?

edit: Stupid. The problem was that I got a string with value 'null'
How to compare for null in groovy correctly?
I've got the following script
println "row6: " + row[6]
if(row[6] == null) {
println "if"
}
else {
println "else"
}
When I run it with a row where the specified field is null this is the output:
row6: null
else
The Groovy Docs say a == null will work, while a.is(null) will not.
So how do I compare for null in groovy the right way?
P.S. I saw The SO-Thread: comparing-null-and-number-in-groovy. It says that null is handled as a number, but this would still mean a == comparision should work when the value is null.
This code prints if:
def row = []
row[6] = null
println "row6: " + row[6]
if(row[6] == null) {
println "if"
} else {
println "else"
}
Are you sure that row[6] is null?

How to handle if no rows returned in Groovy

I have the following piece of code:
sql.eachRow(query){
def i=1
println("$i --> $it.columnName")
i++
}
If query returns some records(rows), there is no problem.
But if query is returning 0 records then how should I handle it. I want to show a user-friendly message, such as ZERO RECORDS FOUND.
def i=0
sql.eachRow(query) {
i++
println(i+" --> "+ it.columnName)
}
if (i == 0) {
println "ZERO RECORDS FOUND"
}
def rows = sql.rows(query)
if (rows.empty) {
// logic for handling no rows
} else if (rows.any { it.name == 'something' }) {
// logic for handling isExists == true
} else {
// logic for handling isExists == false
}
I'm not sure what's your specific case is, but it may be a case that checking name == 'something' condition can be done straight away at SQL level with WHERE name = 'something'. Then you could get rid off one of logical blocks in if statement.

Resources