I'm trying to write a program that that will find if there's an equal number of odds and even numbers in a given one, it's working great but it want to use conditional operator instead of these 4 rows (the // rows),
I'm getting this:
Syntax error on token "%", invalid AssignmentOperator
Can someone tell me why? What's wrong?
while(number!=0) {
//if(number%2==0)
//even++;
//else
//odd++;
number%2==0 ? even++ : odd++;
number/=10;
}
number%2==0 ? even++ : odd++;
This is not a statement. The result of a ternary must be assigned to something:
int x = number % 2 == 0 ? even++ : odd++;
However, this is stylistically quite awkward. I would use an if-else (i.e., what you originally had) over this pattern. Here you've created a temporary variable that you're never going to reuse, for the sole purpose of using a ternary.
It requires a variable at the left side at where you can place the value after the condition.
int tmp = (number%2 == 0)?even++:odd++;
number%2==0 ? even++ : odd++;
This statement is not assigning any value to number.As per my knowledge its always recommended for use if-else instead of ternary operator.
Because, in ternary operator the false/else part is compulsory to write, where in if-else else/false part is optional.
while(number!=0) {
//if(number%2==0)
//even++;
//else
//odd++;
int temp= number%2==0 ? even++ : odd++;
number/=10;
}
Now, temp variable is holding the value .
Related
I want to write single line if else check. But i am getting error.
Please help
if(x == 1) {
System.out.println("aaa");
}else {
System.out.println("bbb");
}
Is there a way to make above code as single like below. Getting compile error in below line
x == 1 ? System.out.println("aaa") : System.out.println("bbb");
Please help. I might be making a silly error i guess.
The second and third arguments of the conditional ternary expression must be expressions, so they can't be System.out.println("aaa").
Instead, so you can write:
System.out.println (x == 1 ? "aaa" : "bbb");
Now you have a ternary conditional expression that produces a value (either "aaa" or "bbb"), and that value is passed to System.out.println.
The ternary operator can only be used with expression returning a value. In your case, System.out.println("aaa") is not expression and can't be used.
You can use:
System.out.println(x == 1 ? "aaa" : "bbb");
I'm a beginner in coding. I was recently working with to create a chatting programme where a user will chat with my computer. Here is a part of the code:
System.out.println("Hello, what's our name? My name is " + answer4);
String a = scanner1.nextLine();
System.out.println("Ok, Hello, " + a + ", how was your day, good or bad?");
String b = scanner2.nextLine();
**if (b.equals("good"))** { //1
System.out.println("Thank goodness");
} else **if (b.equals("it was good"))** { //2
System.out.println("Thank goodness");
} else **if (b.equals("bad"))** { //3
System.out.println("Why was it bad?");
String c = scanner3.nextLine();
System.out.println("Don't worry, everything will be ok, ok?");
String d= scanner10.nextLine();
} else **if (b.equals("it was bad"))**{ //4
System.out.println("Why was it bad?");
String c = scanner3.nextLine();
System.out.println("Don't worry, everything will be ok, ok?");
String d= scanner10.nextLine();
}
if(age<18){System.out.println("How was school?");}
else if (age>=18){System.out.println("How was work?");}
The conditions of the if statements are in Bold (surrounded with **). In case of first and the second condition I want my application to do same thing. Similarly third and fourth condition. I thought it was possible to somehow group them in if statement.
I tried with below code but it doesn't compile:
if (b.equals("good"), b.equals("it was good")) {
System.out.println("Thank goodness");
} else if (b.equals("bad"),(b.equals("it was bad"))) {
System.out.println("Why was it bad?");
String c = scanner3.nextLine();
System.out.println("Don't worry, everything will be ok, ok?");
String d= scanner10.nextLine();
}
Can someone correct it for me?
You can use logical operators to combine your boolean expressions.
&& is a logical and (both conditions need to be true)
|| is a logical or (at least one condition needs to be true)
^ is a xor (exactly one condition needs to be true)
(== compares objects by identity)
For example:
if (firstCondition && (secondCondition || thirdCondition)) {
...
}
There are also bitwise operators:
& is a bitwise and
| is a bitwise or
^ is a xor
They are mainly used when operating with bits and bytes. However there is another difference, let's take again a look at this expression:
firstCondition && (secondCondition || thirdCondition)
If you use the logical operators and firstCondition evaluates to false then Java will not compute the second or third condition as the result of the whole logical expression is already known to be false. However if you use the bitwise operators then Java will not stop and continue computing everything:
firstCondition & (secondCondition | thirdCondition)
Here are some common symbols used in everyday language and their programming analogues:
"," usually refers to "and" in everyday language. Thus, this would translate to the AND operator, &&, in Java.
"/" usually refers to "or" in everyday language. Thus, this would translate to the OR operator, ||, in Java.
"XOR" is simply "x || y but both cannot be true at the same time". This translates to x ^ y in Java.
In your code, you probably meant to use "or" (you just used the incorrect "incorrect solution" :p), so you should use "||" in the second code block for it to become identical to the first code block.
Hope this helped :)
You're looking for the "OR" operator - which is normally represented by a double pipe: ||
if (b.equals("good") || b.equals("it was good")) {
System.out.println("Thank goodness");
} else if (b.equals("bad") || b.equals("it was bad")) {
System.out.println("Why was it bad?");
String c = scanner3.nextLine();
System.out.println("Don't worry, everything will be ok, ok?");
String d= scanner10.nextLine();
}
This is probably more answer than you need at this point. But, as several others already point out, you need the OR operator "||". There are a couple of points that nobody else has mentioned:
1) If (b.equals("good") || b.equals("it was good")) <-- If "b" is null here, you'll get a null pointer exception (NPE). If you are genuinely looking at hard-coded values, like you are here, then you can reverse the comparison. E.g.
if ("good".equals(b) || "it was good".equals(b))
The advantage of doing it this way is that the logic is precisely the same, but you'll never get an NPE, and the logic will work just how you expect.
2) Java uses "short-circuit" testing. Which in lay-terms means that Java stops testing conditions once it's sure of the result, even if all the conditions have not yet been tested. E.g.:
if((b != null) && (b.equals("good") || b.equals("it was good")))
You will not get an NPE in the code above because of short-circuit nature. If "b" is null, Java can be assured that no matter what the results of the next conditions, the answer will always be false. So it doesn't bother performing those tests.
Again, that's probably more information than you're prepared to deal with at this stage, but at some point in the near future the NPE of your test will bite you. :)
You can have two conditions if you use the double bars(||). They mean "Or". That means only ONE of your conditions has to be true for the loop to execute.
Something like this:
if(condition || otherCondition || anotherCondition) {
//code here
If you want all of conditions to be true use &&. This means that ALL conditions must be true in order for the loop to execute. if any one of them is false the loop will not execute.
Something like this:
if(condition && otherCondition && anotherCondition) {
//code here
You can also group conditions, if you want certain pairs of them to be true. something like:
if(condition || (otherCondition && anotherCondition)) {
//code here
There is a simpler way.
if (b.contains("good")) {
...
}
else if (b.contains("bad")) {
...
}
A nested-if condition to be written using the ? : syntax. Is it not an allowed scenario?
Below is the code
int i=(10>5)?(2<5)?230:456;
System.out.println("i="+i);
Which I thought would be equal to
if(10>5){
if(2<5){
i=230;
}
else{
i=456;
}
}
My idea was that first 10>5 would be evaluated, and as it is true, it would then verify if 2<5 or not. Now since that is also true, "i" should be assigned to 230.
The error message was
ControlFlow.java:10: error: : expected
int i=(10>5)?(2<5)?230:456;
ControlFlow.java:10: error: ';' expected
int i=(10>5)?(2<5)?230:456;
^
ControlFlow.java:11: error: illegal start of expression
System.out.println("i="+i);
^
ControlFlow.java:11: error: ';' expected
System.out.println("i="+i);
You forgot to add a part of the expression. Try it as follows:
int i = (10>5) ? ( (2<5) ? 230:456 ) : 0;
Replace the above 0 to be the desired number you want your variable to be when your first condition (10>5) is false.
The ternary operator has the syntax
aBoolean ? value : value
and it will return a value itself, so you can nest them as
aBoolean ? (aBoolean ? value : value) : value
Your code (10>5)?(2<5)?230:456; however is equivalent to
aBoolean ? (aBoolean ? value : value)
so it is missing the second value for your first ternary operator.
Sometimes it may be easier to understand if you rearrange the conditions.
Instead of
int v = (a > b) ? (c > d) ? 100 : 200 : 300;
You can do
int v = (a <= b) ? 300 : (c > d) ? 100 : 200;
The only difference is in the latter case, the initial condition returns a value immediately when true and requires requires further evaluation when false.
Yes you can nest the ternary operator as deep as you can next the if conditions however, ternary operators being the condensed version of IF conditions, they can make ur code not readable if you condense them deeper.
Just remember to bracket the conditions just to make it readable but it's not a requirement (0<1) ?
You can go for below solutions. But this is not recommended today as Cognitive complexity of a source code is a considerable matter in industry today. According to the logic which you have shared the same can be implmented in both ways as below.
int i=(10>5) && (2<5)?230:456;
System.out.println("i="+i);
int i = (10>5)?(2<5)?230:456:0;
System.out.println("i="+i);
I have a piece of code that uses a conditional operator to compare the value of the variable x to 5:
(x >=5 ? x : -x)
What benefit is there to using a conditional operator over a regular if else statement?
Note that is ?: is an expression - it returns a value which must be consumed
z = (x >=5 ? x : -x)
The if construct in Java is not an expression (there are languages where it is) and does not return a value so in this sense they are not equivalent.
An example where they are equivalent is when the if options perform an assignment:
if("Cheese".equals(x)) {
type = "Dairy";
} else {
type = "Maybe not dairy";
}
this is the same as
type = "Cheese".equals(x) ? "Dairy" : "Maybe not dairy";
You can nest ?: to arbitrary depth but really shouldn't - it becomes quite difficult to read:
List<String> cheeses = Arrays.asList("Gouda", "Edam");
String x= "Gouda";
String type = cheeses.contains(x) ? "Gouda".equals(x) ? "Yummy Gouda" : "Cheese - but not Gouda" : "Maybe not dairy";
Ternary operator is not the equivalent of if-else in EVERY possible case. This is because both of possible results of using ternary operator are return values (e. g. simple printing to the console is not a return value so it can't be one of possible results in ternary operator).
Look, you can do it with if-else, but it's not possible with ternary operator:
if (x > 5) {
System.out.println("Statement is true");
else {
System.out.println("Statement is false");
}
You can't do it with ternary operator:
x > 5 ? System.out.println("Statement is true") : System.out.println("Statement is false");
When both of results of using ternary operator are considered as return values, they are then an equivalent of if-else.
Yes, it can be used, but off course in that case using -x doesn't make sense so it depends on what do you want to return when String is an input. You can do this:
("Cheese".equals(x) ? <some object of expected type X> : <some other object of expected type X>)
where X can be String on any other type. And remember to do "string".equals(x) instead of x.equals("string"). This prevents NullPointerException.
For primitive values you can use ==, but for objects you need to use equals method. There are some edge cases when you can use == on String, but they are not relevant to your case I guess and you can read about it outside of this topic.
PS: Some answers talk about if else statement, but that's not what question is about.
Can this be used like an if else on all accounts? For example, can you
compare strings with it?
I am pretty sure that by saying like an if else he means conditional operator which has if else like behaviour, not if else instruction itself.
Yes it can be used in Java; however note that x =="Cheese" isn't the proper way to compare strings in Java, you want something like "Cheese".equals(x).
This question already has answers here:
What is the Java ?: operator called and what does it do?
(17 answers)
Closed 10 years ago.
I dont know what the question mark (?) stand for in java, I was doing a small program, a Nim-game. were looking in a book, for help and saw this statement:
int pinsToTake = (min >= 2) ? 2 : 1;
I don't understand it, what will ? represent, can it be something to do with if-statement but you put it in a variable? and the : can be something "else"? (this things that I just said can be very misleading)
someval = (min >= 2) ? 2 : 1;
This is called ternary operator, which can be used as if-else. this is equivalent to
if((min >= 2) {
someval =2;
} else {
someval =1
}
Follow this tutorial for more info and usage.
Its ternary operator also referred to as the conditional operator, have a look reference
like Object bar = foo.isSelected() ? getSelected(foo) : getSelected(baz);
eg. operand1 ? operand2 : operand3
if operand1 is true, operand2 is returned, else operand3 is returned
operand1 must be a boolean type
operand1 can be an expression that evaluates to a boolean type
operand1 and operand2 must be promotable numeric types or castable object references, or null
if one of operand2 or operand3 is a byte and the other a short, the type of the returned value will be a short
if one of operand2 or operand3 is a byte, short or char and the other is a constant int value which will fit within the other operands
range, the type of the returned value will be the type of the other
operand
otherwise, normal binary numeric promotion applies
if one of operand2 or operand3 is a null, the type of the return will be the type of the other operand
if both operand2 and operand3 are different types, one of them must be compatible (castable) to the other type
reference
it means:
if(min >= 2)
someval =2;
else
someval =1
Its called a ternary operator
See this java example too
That's a Ternary Operator. Check Oracle's doc for further info. Long story short, it is an if-else statement that can be done in a single line and used inside methods and to define variable values.
Syntax:
boolean_expression ? do_if_true : do_if_false;
Parallelism with if-else statement:
if(boolean_expression)
//do_if_true;
else
//do_if_false;
I didn't use brackets on purpose, since you can only execute one line of code in do_if_true and do_if_false.
Example of use:
boolean hello = true;
String greetings = hello ? "Hello World!" : "No hello for you...";
This will set someString as "Hello World!" since the boolean variable hello evaluates to true. On the other hand, you can nest this expressions:
boolean hello = true;
boolean world = false;
String greetings = hello ? (world ? "Hello World!" : "Hello Stranger!") : "No hello for you...";
In this case, greetings will have as a value "Hello Stranger!";
It's called the Ternary If operator, it's just short-hand for an if...else
"? :" is a ternary operator equivalent to an if else statement.
In your example:
pinsToTake = (min >= 2) ? 2 : 1
if min >= 2 then assign 2 to pinsToTake, else assign 1
max = (a > b) ? a : b;
(a > b) ? a : b; is an expression which returns one of two values, a or b. The condition, (a > b), is tested. If it is true the first value, a, is returned. If it is false, the second value, b, is returned. Whichever value is returned is dependent on the conditional test, a > b. The condition can be any expression which returns a boolean value.
It is called conditional operator.This is how it works.
if min is greater than or equal to 2 ,then first value after ? that is 2 here will be assign to corresponding variable ,otherwise second value that is 1 here will be assign.
This link will tell you all you need.
Summary for archival sakes:
It's called the conditional operator. It's a ternary operator that
takes three terms:
BooleanExpression ? Expr1 : Expr2
The BooleanExpressionis evaluated. If it's true, the value of the
whole expression is Expr1. If it's false, the value of the whole
expression is Expr2.
So it serves the same kind of purpose as an if statement, but it's a
term rather than a whole statement. That means you can embed it in
places where you can't use a whole statement.