about java calculation expressions [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 12 days ago.
Improve this question
import java.util.\*;
class Example{
public static void main(String asrg\[\]){
boolean b = false;
System.out.println(10\>4 && true !=b==(10+3/2==8)==true); //Line 1
}
can anyone explain this expression?
expecting the steps how to calculate these

The code provided is missing a final curly brace ('}') and will not compile. There are also some backslashes ('\') strung about that will result in syntax errors. Additionally, 'args' is misspelled but it is not necessary in order for code to compile.
With the final brace added and backslashes removed, the code is:
import java.util.*;
class Example
{
public static void main(String args[])
{
boolean b = false;
System.out.println(10>4 && true !=b==(10+3/2==8)==true); //Line 1
}
}
Running the above code will display the answer in console. However the steps can be explained below.
First, we need to simplify our boolean expression into just terms of true and false. Since we declare that b = false, and the fact that10 > 4 == true and (10+3/2==8) == false, the expression that is printed can be simplified to (true && true != false == false == true).
The expression can then be evaluated according to Java's operator precedence, and will evaluate to false.

Your code won't compile; It's missing a } at the end of the class.
Also, did you copy and past this from a website? Why are there \ all over the place?
For better readability, use the Java-style array declaration: String[] args instead of String args[].
To check a boolean value, you don't have to compare it to true or false. This includes any actual booleans, or expressions outputting a boolean, such as: 10 + 3 / 2 == 8, which is false.

Related

OCA8 Java Certification question - Java Operators [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
Came across this question in one of practice exam for OCA java certification:
Which statements about the output of the following programs are true?
int i = 0;
boolean bool1 = true;
boolean bool2 = false;
boolean bool = false;
bool = (bool2 & method1("1")); //1
bool = (bool2 && method1("2")); //2
bool = (bool1 | method1("3")); //3
bool = (bool1 || method1("4")); //4
}
public static boolean method1(String str) {
System.out.println(str);
return true;
}
The answer given is it prints 1 and 3
Can some one please explain me the solution?
2 and 4 are not printed because only the first part of the expression is evaluated in those cases.
For the && Operator it doesnt matter what the second expression is, if the first expression is already false. So it is not necessery to evaluate the second part.
if(false && true)
is the same as
if (false)
For the || Operator it is vice versa, if the first expression is already true it is not necessary to evaluate the second part. Therefore your method is not called.
if(true || false)
is the same as
if(true)
But keep in mind that if you switch your expressions, like so:
bool = (method1("2") && bool2);
Your method would be called. Thats because your first part of the Expression is true, so the whole expression could be true. Therefore the second part needs to be evaluated too.
Try
bool = (method1("2") && method1("2") );
bool = (method1("2") || method1("2") );
and see what´s happening.
& and | are bitwise comparators and therefore every part of your expression is evaluated. Therefore your method is called.

Single equal in different situation [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
I have this code...
class Test {
public static void main(String[] args) {
Boolean mySuperBoolean = Boolean.FALSE;
System.out.print("a");
if (mySuperBoolean = Boolean.TRUE) {
System.out.print("b");
}
System.out.print("c");
}
}
I am new to Java, but I knew single equal (=) is used to assign. And double equals (==) is used to check if object is referred to the same location in memory. However, in this case I do not understand how the 'b' is being printed with a single equals, but I understand changing it to a double equals sign will not print it out
if (mySuperBoolean = Boolean.TRUE) will assign Boolean.TRUE to your mySuperBoolean variable and the condition will evaluate to true, hence whatever is inside your if it will always execute
The result of the assignment operator = will be the assigned value. So if (mySuperBoolean = Boolean.TRUE) will always evaluate to true.
Assignment is an expression which resolves to whatever was assigned, in this case(mySuperBoolean = Boolean.TRUE) is an expression which resolves to Boolean.TRUE.
This is really only useful in a few specific situations. One such case is the following idiom:
String line;
while ((line = readLine()) != null) {
//...
}
Or even
i = j = k = 0; // equal to: i = (j = (k = 0))
It's a controversial feature because it allows probable bugs such as yours to compile successfully. To mitigate this, some people will invert the operands (a "yoda condition"):
if (Boolean.TRUE == mySuperBoolean)
This works because if I forget the second equals then the compiler will throw an error because Boolean.TRUE is final and cannot be assigned to.
In essence, what happens here boils down to:
if (Boolean.TRUE) {
System.out.print("b");
}
That assignment puts TRUE into the variable, the variable is boolean, and checked for its current value, end of story.

Can I return Boolean value in a loop statement? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I just came up with a problem returning a Boolean value in accordance with a given condition. I thought in order to check the given condition for full possibilities I need to use for loop. But when I tried to compile it, it gives me error, possibly because there is uncertainty returning a Boolean value using for loop. Here is an original problem:
Return true if the given string contains a "bob" string, but where the middle 'o' char can be any char.
bobThere("abcbob") → true
bobThere("b9b") → true
bobThere("bac") → false
And here is my code:
public boolean bobThere(String str)
{
for(int i=0; i<str.length()-3; i++)
{
if (str.length()>=4): && str.charAt(i)=='b' && str.charAt(i+2)=='b')
{
return true;
}
else
return false;
else if (str.length()==4 && str.charAt(0)=='b' && str.charAt(2)=='b')
{
return true;
}
else
{
return false;
}
}
}
I just wanted to ask :
1. Can I fix the this code for returning a value. I mean, can I use for loop and return specific value for a given condition? If yes, please could you give me a sample.
2. Or are there any ways other than for loop to solve this problem.
Thanks in advance.
The compiler error is almost certainly because you have an elseif after an else. That's invalid.
Looking at your code, what you seem to want to do is loop through the string, and then return true if you're at the start of a b?b string. I'm not sure why you have your second if condition in there - at the moment your code would check the first and third characters of the string on every iteration of the loop, if the string happens to be exactly four characters long. Pointless, it doesn't need to be there. The check for length isn't necessary at all.
Additionally, your end condition for the loop is currently i < string.length()-3. This means that the final three characters of the string will not be checked. You would need to change this to either i <= string.length()-3 or i < string.length()-2 to solve this.
Your else return false stuff is going to give you a serious problem. Your code will enter the loop once, and then either return true or false, without ever going to the next phase of the loop. What you should do is loop through the string, and if you find what you're looking for, return true. Otherwise, don't return at all, and keep going with the loop. If you get to the end of the loop it means you never found what you were looking for, so you can at that point return false.
Taking those comments into account, your revised code would look like this (please note I haven't compiled or run this):
public boolean bobThere(String str)
{
for(int i = 0; i <= str.length() - 3; i++)
{
if (str.charAt(i) == 'b' && str.charAt(i + 2) == 'b')
{
return true;
}
}
return false;
}

Clarification on "!" operator in java [duplicate]

This question already has answers here:
Using NOT operator in IF conditions
(8 answers)
Closed 7 years ago.
I have a boolean variable collision initialized to false.
Now in an if statement, suppose my if condition is the following:
if(!collision)
does this mean that the if statement will execute if collision is the opposite of what is initialized? Meaning, will it execute when !collision returns true?
Just a bit confused since I initialized it to false, and I want this if statement to run when collision is false, but don't know if !collision is the right way to do it or not.
Code as requested. Still confused on what the condition would be. I have collision initialized to false. As a result, I want the statement to be executed when it is false. Should I write if(collision) or if(!collision)?
boolean collision = false;
boolean winner = false;
while(!winner){
//Main loop where user will be able to move the ships and try to destroy the ship
//boolean shipAlive = true/false; YET TO ADD!
//if(!shipAlive) -> winner = true; YET TO ADD!
//movement of ships
if(!collision){
System.out.println("Player 1: L, R, or S? (L = Left, R = Right, S = Stay)");
String p1Input = IO.readString();
int k = movement(p1Input, player1);
while (k == 1){
System.out.print("Error! Enter either L, R or S: ");
p1Input = IO.readString();
k = movement(p1Input, player1);
}
}
collision = fireProjectileUp();
if(collision){
winner = true;
}
Yes, it is the right way to do it:
In if (!someBoolExpr) { ... }, the "then-clause" will run if someBoolExpr == false.
See the JLS §15.15.6: Logical Complement Operator ! for more information:
The value of the unary logical complement expression is true if the (possibly converted) operand value is false, and false if the (possibly converted) operand value is true.
! represents NOT in Java. So if you have something like
if(!true) {
//doSomething
} else {
//Something else --- This is executed.
}
if(!false) {
//doSomething --- This is executed.
} else {
//Something else
}
true and false are the final result of your comparison operations
! means not, so your expression will be translated to if(NOcollision).
Check documentation for further info.
Yes, your if statement will be executed when collision is false.
!false returns true
You've asked a question, but I suspect this is a bit of an XY problem for you. You've asked about clarification of the ! operator, then proceeded to explain exactly what a not operation is.
When constructing your conditions, you want to manipulate the logic so that it evaluates to true when you want it too. For example, I want something to run if there has been a collision.
if(collision)
Simple. This is because this will evaluate to true when you want it too. Now you want something to run if their hasn't been a collision.
if(!collision)
Once again, it evaluates to true if collision is false. Or, when you want it too. The trick here is working out how to express what you want in a way that the compiler understands, and this is done through logical expressions that resolve to some boolean true or boolean false.
EDIT
Just incase, ! operator is simply the opposite of the value. !true is false, !false is true. Going by what I explained above, you can combine this knowledge to create your solution.
When if(!collision) is executed then first of all it checks the value of collision. Let's assume its is 'false'. Then ! operator converts it to true. opposite of false. Then the value is 'true ' so, if statement will execute its code block.

How did I get the result of '6.03' and '23.24'? - Java Parameter Return [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I wonder how did I get the result of '6.03' and '23.24'? System.out.println(a+b+c) does not add up to those 2 numbers?
Why is there a return c + "" + a? There is no output result show c + a?
The full code as follows:
MyProgram:
public class MyProgram
{
public void start()
{
String result;
result = lots(2+1, 3, "3");
result = lots(22, 1.2, "4");
}
private String lots(int a, double b, String c)
{
System.out.println(a+b+c);
return c + "" + a;
}
}
MyApplication:
public class MyApplication
{
public static void main (String[] args)
{
MyProgram p = new MyProgram();
p.start();
}
}
It makes sense because you're concatenating some string at the end of all of that math.
For the first run, you pass in 3 and 3.0 as your first two numerical parameters. That adds to 6.0 (it's been since upcast to double). You now then do string concatenation on 3 to arrive at 6.03 for your answer.
Trace through the second execution of the method to arrive at a similar answer. Remember: + is overloaded in Java to mean either numeric addition or string concatenation.
You overwrite result after you get it the first time, but even then, you don't do anything with it. I'd argue that you don't really need the return statement. If it were there, then you'd actually return the string 422*, since again, it's all string concatenation at that level.
*: This is from the last standing run if you printed it out after both were executed. If it were printed out each time, you'd see 22 first.
a+b+c is (a+b)+c
The first addition adds the two numbers.
The second addition converts the result of the addition into a string, then concatenates it with the final string.
So ((2+1) + 3) = 6.0
and 6.0 + "3" = "6.0" + "3" = "6.03"

Categories

Resources