hi. i got the task right, (you can see the if/else statement commented out), but afterwards i wanted to use the ternary operator instead. i can't seem to get it right as the statement gets an error that the void type isn't allowed here. can anyone help me understand what's going on and let me know how to use it correctly?
public class Solution {
public static void main(String[] args) throws Exception {
int sum = 0;
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
boolean test = true;
while (test){
String nextString = reader.readLine();
// here is the old if statement
/*if (nextString.equals("sum")){
System.out.println(sum);
test = false;
} else {
sum += Integer.parseInt(nextString);
}*/
// and here is the attempt to convert it.this line spits error.
(nextString.equals("sum"))?(System.out.println(sum)) && (test = false):sum += Integer.parseInt(nextString);
}
}
}
how do i use the ternary operator her?
Resolved
Comments (2)
- Popular
- New
- Old
You must be signed in to leave a comment
Gellert Varga
27 May 2020, 22:10solution
1)
A) && : This is a logical "AND" operator. Which can only be executed between two booleans.
B) If you want to execute two or more commands one after the other, put a comma between them.
(But I don't think this will comply with the 'clean code' principle...)
2) The ternary operator is not used to execute commands or command blocks.
Instead, it is used for assignment.
For example:
3) But You can combine it with returning methods:
4) I read about the ternary operator somewhere that there are places where its use is prohibited because it impairs the readability of the code. +1
bob
30 May 2020, 22:31
thanks for that info. very helpful
0