If-then-else statement use - java

Method: “run”
Create endless loop
If MerkleManager.sMerkleRoot is not null then...
If the above merkle root equals the initial user-entered merkle root.Then print out “You win: “ followed by the merkle root and exit the app.
Else if they’re not equal, then tell the user he lost – and exit the app.
My code:
public void run() {
while (true) {
}
if MerkleManager.sMerkleRoot = null;
{
} else {
}
System.exit(0);
}
How do I set MerkleManager.sMerkleRoot not null and use if-then-else statement?

In your check you are assigning the value of MerkleManager.sMerkleRoot with "=" assignment operand.
Instead you should be checking "==" or "!=" operand to compare the object references.
public void run() {
while (true) {
}
if MerkleManager.sMerkleRoot != null
{
} else {
}
System.exit(0);
}

Your code will never leave the while loop the way it's written.
Change to this,
public void run() {
while (true) {
if MerkleManager.sMerkleRoot != null{
// do stuff
}else {
// do something else
}
System.exit(0); // if you leave this statement, your code will exit on the first exec
}

First off, you are saying that you want it to exit the JVM whether the condition is met or not which would render the while loop useless as the first iteration would guarantee a termination for either case (and the way you have it currently will get you stuck in the loop and never execute the following line anyways) so you can remove that completely.
Second, you need parentheses around the boolean statement in an if clause in java.
What you want to do for your method might look a little more like this
public void run() {
if (MerkleManager.sMerkleRoot != null && MerkleManager.sMerkleRoot == inputRoot) {
System.out.println("You won");
}
else {
System.out.println("You lose");
}
System.exit(0);
}

Related

Java break; won't work is intended... What is wrong with this structure?

I want only the while loop to start over if the if condition inside is true.
In my book this is achieved with breaking the loop, to let it start over.
Problem with this code is: The break does nothing but stopping the while loop. If the if condition is true, nothing gets repeated. The method returns the value of x and it is over.
How can I get the while loop repeat if the if condition is met, in this example?
Thank you :)
public int example() {
for() {
if() {
//code
}else{
z=0;
while (z==0) {
//code
if() {
//code
break;
}else{
z=1;
}
}
}
}
return x;
}
Here break; keyword is breaking the whole while loop if condition is true. And as the code has nothing else to execute after while loop has ended, the code returns 'X'.
I suppose that is not what you want.
You can either use continue keyword instead of break.
Or you can consider refactoring a method out of:
//code
if() {
//code
break;
}else{
z=1;
}
like below:
public boolean condtionalRepeat(){
//code
if() {
//code
return true;
}else{
return false;
}
}
and the code will look like:
public int example() {
for() {
if() {
//code
}else{
//code
while (condtionalRepeat()) {
//code
}
}
}
return x;
}
An additional comment on the original code: if this is accurate:
while (z==0) {
//code
if() {
//code
break;
}else{
z=1;
}
}
then it collapses to
//code
if() {
//code
}else{
z=1;
}
The loop never loops. The first time through (in the original code) either the 'if' condition is satisfied, or it is not satisfied.
If satisfied, we end with a 'break' out the loop.
If not satisfied, we set z to 1, then loop to evaluate the 'while' condition, which terminates the loop.
Either way the loop executes once only.

while(true) loop only executes once

I wrote a piece of code which should be executed until the condition is satisfied. I have 2 classes using the same structure. In one of them while (true) loop executes as expected; in the other class the program exits the loop after the first recursion.
protected static boolean flag = true;
private static int value=0;
private static int limit=10;
.
.
.
public static int method(){
if (limit-value <=0)
{
...
}
else {
while(flag) {
if (limit-value > 0 ) {
*the action I want to perform until the condition is satisfied*
value++;
}
else if (limit==value)
{
flag = false;
}
return int_Value;
}
}
}
return int_Value;
}
I expect the while(true) loop to be executed until the condition is satisfied (which is more than once).
With some cleaned up indentation it becomes clear that the while loop contains an unconditional return.
if you look at your code the while loop goes like this
while(flag) {
if (limit-value > 0 ) {
*the action I want to perform until the condition is satisfied*
value++;
}
else if (limit==value)
{
flag = false;
}
return int_Value;
}
after executing either if or if else statement there is a return int_value statement which is causing the problem
Although I did debugging I couldn't see it in the first place. I performed another debug session after #user3437460 's suggestion, so I was able to find out:
It seems like an additional return statement was used!(return int_Value;),
the one after else if block. So, the program returns a value and never goes back into the loop.
After deleting the first return statement, program runs just fine.

How to return a break or Continue in a method is it possible?

When I'm using while loop I need to use many if blocks which are exactly same So I planed to put it in a method and reuse it where I want! but I had a problem I want to return Continue or break in some area of my if blocks so can I return Break or continue?
while (true){
move(a);
move(b);
}
public *** move(Parameter parameter){
if (statement){
return continue;
}
else{
return break;
}
}
You can return a boolean:
while (true){
if(move(a))
{
break;
}
else
{
continue;
}
if(move(b))
{
break;
}
else
{
continue;
}
}
public boolean move(Parameter parameter){
if (statement){
return false;
}
else{
return true;
}
}
I'm going to set aside the fact if we implemented what you want literally then move(b); would be unreachable. Presumably when you say continue you mean execute the next statement; not return to the start of the loop?
But sadly you can't achieve this in Java. In Java, you can only return a value, not an "instruction". (In C and C++ you can contrive this using a macro, although that messes up your debugger.)
However, if you adapt move to return a boolean which is say true if you want to break and false otherwise, then at the call site you could write
while (true){
if(move(a)){
break;
} else if (move(b)){
break;
}
}
or ace it with
while (true){
if (move(a) || move(b)){
break;
}
}
where I'm exploiting the short-circuiting nature of the operator ||.
Finally, if you want to submit this code to an obfuscation contest then use the simply beautiful but still comprehensible
while (!(move(a) || move(b)));
and if you want to guarantee that you win said contest, then swap the return rule of move round and use the utterly indecent
while (move(a) && move(b));
Make it super simple with a returning boolean
public boolean move(Parameter parameter){
return statement;
}
while (true){
if(!move(a)) break;
if(!move(b)) break;
}

Return statement function in if conodition

In my code:
if (id.isEmpty() || name.isEmpty()) {
warlbl.setText("Warning, Empty ID or Name Fields");
return;
}
id and name are String that give from JTextFields ,
Is necessary use return; in here or Not?
Yes, it can be:
if (...) {
...
return;
}
// nothing at this point will be reached if the if-statement is entered
vs.
if (...) {
...
}
// code here will still be reached!
return exits the current method you are "in".
Of yource it is not necessary but maybe you want to exit the method if id.isEmpty() and name.isEmpty(). So no and yes. It is not neccassary but you may want to return
You can use return to break out of a method, continue to skip a loop or a break to break out of a block.
Often there are 2 ways:
public void test() {
if (!statement) {
// to something if statement is false
} else {
//we failed, maybe print error
}
}
or:
public void test() {
if (statement) {
//we failed, maybe print error
return;
}
//do something if statment is false
}
But this is more a kind of "style". Mostly I prefere the second way, just because it's less spagetti :P
Keep in mind. If your return statement would be the last statment executed it's redundant.
Java reference:
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/branch.html

If statements not being detected

I am using Netbeans 7.1.2 IDE.
My code is here:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
String search1;
search1 = jTextField1.getText();
search1.toLowerCase();
jTextField2.setText("tes1");
// stone
if (search1=="stone" || search1=="rock" || search1=="1")
{
jTextField2.setText("Stone: 1");
}
// grass
else if (search1=="Grass" || search1=="grass")
{
jTextField2.setText("Grass: 2");
}
// dirt
else if (search1=="Dirt" || search1=="dirt" || search1=="Soil" || search1=="soil")
{
jTextField2.setText("Dirt: 3");
}
// cobblestone
else if (search1=="cobblestone" || search1=="cobble")
{
jTextField2.setText("Cobblestone: 4");
}
else;
{
jTextField2.setText("Unknown Block");
}
}
When I run the build, and I input 'stone' into jTextField1, and hit jButton1, it just gives me "Unknown Block", when an If statement specifies that it should set jTextField to "Stone: 1". Am I doing something wrong? Sorry if this ends up being a completely obvious error.
Compare String using equals()
if (search1.equals("stone") || search1.equals("rock") || search1.equals("1"))
Read this for more information.
== compares references,not the values. In your case, you want to check for the value equality, not the reference equality.
EDIT:
Remember, you need to do all your String comparisons that way.
Besides,
you have an unwanted ; here:
else;
{
jTextField2.setText("Unknown Block");
}
remove that ; after else.
You need to use the .equals to check strings, like so:
if (search1.equals("stone") || search1.equals("rock") || search1.equals("1"))
So first don't compare String using == but use equals() instead then in the last else statement you have add a ; that means the end of the else (so jTextField2.setText("Unknown Block") is always executed). You should drop it.
else; //<==Remove the ;
{
jTextField2.setText("Unknown Block");
}
You should do what Kazekage Gaara is telling. But in this instance the problem is not that. in the following statement remove the ; after else.
else;
{
jTextField2.setText("Unknown Block");
}
What happens here is
{
jTextField2.setText("Unknown Block");
}
gets executed anyway because it's after the if else blocks. Semicolon effectively terminates the else statement.
Use .equals instead of == to comapre strings.
See: http://blog.enrii.com/2006/03/15/java-string-equality-common-mistake/

Categories