Not sure I understand this nested ternary operation - conditional-operator

Could use some help understanding (or help with corrections), and either an explanation or link as to how you know so I can figure these out when I run into them again. None of the tutorials I found were terribly helpful. Here's the operation. The bracket denotes a time series (array):
a = b==1 ? c ? d : e > a[1] ? e : a[1] : c ? d : a[1]
Translated, would be:
a = if b==1 and c then d
else if e > a[1] then e
else a[1]
else if c then d
else a[1]
...right? If correct, I don't understand how an else can come between two else-ifs. Doesn't the chain stop evaluating after the first else? I thought else essentially means "otherwise."

I believe the execution would be equivalent to this instead of b == 1 and c:
function test() {
if (b==1) {
if (c) {
return d;
} else {
if (e > a[1]) {
return e;
} else {
return a[1];
}
}
} else {
if (c) {
return d;
} else {
return a[1];
}
}
}
a = test();

Related

In Groovy - How to Iterate the versions in the list?

I am performing below task in jenkinsfile using groovy. where i have below variables
list C=[1.1,1.2,1.3]
String A=1.1
String B=1.3
if ("${A}" == "${B}") {
echo "No Action needed"
} else if ("${A}" != "${B}") {
then check in the variable list C and then iterate the list in sequential order.
}
Need Help in this condition. I am newbie in groovy.
When the A is != to B then it check the version from list C
Expected Output:-
1.1 == 1.3
then check in list C [1.1,1.2,1.3]
Iterate
1.2 ==1.3
print "still need iteration"
1.3 == 1.3
print " Matched"
I have Tried below code but its not doing iteration in for loop for If condition.
def C = ['1.1', '1.2', '1.3']
A=1.1
B=1.3
if ('${A}' == '${B}') {
println "equal"
}
else if ('${A}' != '${B}') {
println "not equal"
for (i = 0; i < C.size(); i++) {
println C[i]
if ('C[i]' == '${B}') {
println "equal"
}
}
}
there are several issues in your code
A,B are numeric and C is array of strings. to compare objects you need same type.
'C[i]' == '${B}' is incorrect because you are comparing literal string 'C[i]' to B converted to GString "1.3"
better to avoid this kind of comparison '${A}' == '${B}' - result could be tricky. better to use A == B
so, your code with changes
def C = ['1.1', '1.2', '1.3']
A='1.1'
B='1.3'
if (A == B) {
println "equal"
} else {
println "not equal"
for (i = 0; i < C.size(); i++) {
println C[i]
if (C[i] == B) {
println "equal"
}
}
}
result:
not equal
1.1
1.2
1.3
equal

Inverse the input Expression using stacks

I had a coding challenge as one of the process for recruitment into a company. In that coding challenge, one of the question was to inverse an expression.
For Example,
Input : 14-3*2/5
Output : 5/2*3-14
I used stack to put each number say 14 or 3 and expressions and then popped it out again to form the output.
Input format is : num op num op num op num
So we need not worry about input being -2.
num can be between -10^16 to 10^16. I was dealing with strings completely, so even if the number exceeds the 10^16 limit, my algorithm wouldn't have any problem.
My algorithm passed 7 test cases and failed in 2 of them.
I couldn't figure it out what the corner case would be. I couldn't see the test cases as well. Any idea what that might be. I know there isn't enough information, but unfortunately I too don't have them.
// Complete the reverse function below.
static String reverse(String expression) {
expression = expression.trim();
if(expression == ""){
return "";
}
Stack<String> stack = new Stack<String>();
String num = "";
for(int i=0; i<expression.length(); i++){
char c = expression.charAt(i);
if(c==' '){
continue;
}
if(c == '+' || c == '-' || c == '*' || c == '/'){
if(num != "") {
stack.push(num);
}
num = "";
stack.push(Character.toString(c));
} else{
num += c;
}
}
if(num != "") {
stack.push(num);
}
String revExp = "";
while(! stack.empty()){
revExp = revExp + stack.pop();
}
return revExp;
}

Return to menu language GO

I have a menu option with two options: add and substract. When I choose one it runs ok but the program closes. I would like to know how to make it go back to the menu after an operation ends to select another one
package main
import (
"fmt"
)
func main() {
var n1, n2, s, r float64
var op, ns int
fmt.Println("\n\tWelcome")
fmt.Println("Chose an option")
fmt.Println("1.-Add")
fmt.Println("2.-Substract")
fmt.Scan(&op)
if op == 1 {
fmt.Printf("\n\tAdd")
fmt.Printf("\nHow many numbers you add? ")
fmt.Scan(&ns)
if ns <= 1 {
fmt.Print("You can not add just a number")
} else {
for i := 0; i < ns; i++ {
fmt.Printf("\nType the number %d: ", i+1)
fmt.Scan(&n1)
s += n1
}
fmt.Println("\nThe sum is: ", s)
//How to return to the menu?
}
} else if op == 2 {
fmt.Printf("\n\tSubtraction")
fmt.Printf("\nType the first number: ")
fmt.Scan(&n1)
fmt.Printf("\nType the second number: ")
fmt.Scan(&n2)
r = n1 - n2
fmt.Println("\nSubstraction is: ", r)
}
}
Just wrap the whole thing in
for {
}
Use break to exit the loop or continue to go back to the top.
It's hard to tell exactly without seeing your code, but I may assume you should use operator for ;; {} and put inside your menu with the appropriate if/else statements.

Method not returning string

I'm writing a method that returns a string for an input of a certain mark. It is given a mark, and then determines the grade that the mark fits into. But it gives me this error:
private String getGrade(int marks) throws Exception{
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
This method must return a result of type String
The code is:
String a = "A, Well done!";
String b = "B, still room for improvement.";
String c = "C, need to improve a lot!";
String d = "D, you got lucky!";
String e = "You failed, please retake the test!";
if (marks>80 || marks==80){
return a;
} else if (marks>70 && marks<80 || marks==70){
return b;
}else if (marks>60 && marks<70 || marks==60){
return c;
} else if (marks>=50 && marks <60){
return d;
}else if (marks<50){
return e;
}
The compiler doesn't try to be smart enough to evaluate all of the possible cases and make sure you will always return a string in all of the branches of your conditional. You need to also have an else clause with no if that will return a default value (which is a string).
It seems like you need a 'else' at the end
String a = "A, Well done!";
String b = "B, still room for improvement.";
String c = "C, need to improve a lot!";
String d = "D, you got lucky!";
String e = "You failed, please retake the test!";
if (marks>80 || marks==80){
return a;
} else if (marks>70 && marks<80 || marks==70){
return b;
}else if (marks>60 && marks<70 || marks==60){
return c;
} else if (marks>=50 && marks <60){
return d;
}else{
return e;
}
As you didnt return a value ifif (marks<50)` statement fails although we know here no posiblity of failing but program runs in this manner only use as i have done
You have to put out else here and return a string value , otherwise statement will not execute . Try it, Hope it will help you.
You can try this it may help you.
String a = "A, Well done!";
String b = "B, still room for improvement.";
String c = "C, need to improve a lot!";
String d = "D, you got lucky!";
String e = "You failed, please retake the test!";
if (marks>=80){
return a;
} else if (marks>=70) {
return b;
} else if (marks>=60){
return c;
} else if (marks>=50){
return d;
} else {
return e;
}
OR
String a = "A, Well done!";
String b = "B, still room for improvement.";
String c = "C, need to improve a lot!";
String d = "D, you got lucky!";
String e = "You failed, please retake the test!";
String r=""
if (marks>=80){
r=a;
} else if (marks>=70) {
r=b;
} else if (marks>=60){
r=c;
} else if (marks>=50){
r=d;
} else {
r=e;
}
return r;
I hope the second one is good because it always have return path and return something to caller.

If-statement with logical OR

public class Test{
public static void main(String args[]){
int a = 0;
int b = 1;
int c = 10;
if ( a == 0 || b++ == c ){
a = b + c;
}else{
b = a + c;
}
System.out.println("a: " + a + ",b: " + b + ",c: " + c);
}
}
Ok, this is Java code and the output is
a: 11,b: 1,c: 10
And I believe the C acts same as Java in this case
That is because second condition(b++ == c) would never executed if the first condition is true in 'OR' operator.
There is a "NAME" for this. I just don't remember what it is.
Does anyone know what this is called??
short circuit evaluation.
This is called short-circuit behavior of the logical operator:
With the short-circuit versions, evaluation of subsequent subexpressions is abandoned as soon as a sub expression evaluates to false (in the case of &&) or true (in the case of ||).

Resources