Java: Breaking Loop - java

What is the best way to implement the following pseudo-code in java?
method_one():
while(condition_one):
EXECUTE method_two(); // (A)
method_two():
while(condition_two):
EXECUTE method_three(); // (B)
method_three():
if (condition_three):
GOTO EXECUTE method_two();
else:
//do some stuff
Edit: Thanks for prompt replies, everybody. Helped a lot. Figured it out now.

If you don't need separate methods, this should be equivalent:
boolean exit_from_three = false;
while (condition_one || exit_from_three) {
exit_from_three = false;
while (condition_two) {
if (condition_three) {exit_from_three = true; break;}
// do some stuff
}
}

I think you could do something like:
public void method_one() {
while (condition_one) {
method_two();
}
}
public void method_two() {
while (condition_two) {
method_three();
}
}
public void method_three() {
if (condition_three) {
return;
} else {
// do something magical
}
}

Assuming I've read the pseudo-code right, it's a pretty simple case of calling methods. The only catch is that whatever represents conditions one, two, and three have to be updated somewhere or this will be an infinite loop at method_two (or method_one).
public class LoopingClass {
private void method_one() {
while(/* condition_one, where condition_one results in a boolean value */) {
method_two();
}
}
private void method_two() {
while(/* condition_two, where condition_two results in a boolean value */) {
method_three();
}
}
private void method_three() {
if(/* condition_three - where condition_three results in a boolean value */) {
return;
} else {
// other stuff here
}
}
}

Related

How to set/call object and method in condition

How is it possible to set an object and method in a condition? I understand that, if the animal is over 50kg it weighs too much. But how about if an animal is hangry, need Love and feel boring return the method feelingNegative()?
I don't know how to set it. But after an animal sleeps, it is hangry. A thought would be:
Animal {
if (hangry == false && needLove == false && boring == false) {
return feelingNegative();
}
}
still don't know how to set it.
public class Animal {
private boolean needLove;
private boolean hangry;
private boolean boring;
private int kg;
public boolean sleep() {
return hangry = true;
}
public boolean watchTv() {
return needLove = true;
}
public void feelingPositive() {
System.out.println("I feel good");
}
public void feelingNeutral() {
System.out.println("Someting is missing...");
}
public void feelingNegative() {
System.out.println("I need love, food and fun!");
}
public void weight(int kg) {
if(50 < kg) {
System.out.println("You ate way too much");
}else {
System.out.println("You need to eat more");
}
}
}
The methods you are calling don't return anything (they are void). Just remove the return. And use boolean negation (!) instead of == false. Like,
if (!hangry && !needLove && !boring) {
feelingNegative();
}
The Method feelingNegative() doesn't return anything (Void). So you just have to define a method that call feelingNegative() when all the conditions are satisfied.
public void myMethod ()
{
if(!hangry && !needLove && !boring)
feelingNegative();
}

Looking for a way to make a java method I wrote more efficient if it possible

private void setIsSelected() {
if (option.equals("length")) {
isSelectedLength.setVisible(true);
} else {
isSelectedLength.setVisible(false);
}
if (option.equals("weight")) {
isSelectedWeight.setVisible(true);
} else {
isSelectedWeight.setVisible(false);
}
if (option.equals("temp")) {
isSelectedTemp.setVisible(true);
} else {
isSelectedTemp.setVisible(false);
}
if (option.equals("area")) {
isSelectedArea.setVisible(true);
} else {
isSelectedArea.setVisible(false);
}
if (option.equals("time")) {
isSelectedTime.setVisible(true);
} else {
isSelectedTime.setVisible(false);
}
}
I feel as if there is a better and more cleaner way of making this method work. The if else statements work however it kind of feels as if I am repeating myself. Any suggestion are gladly welcomed.
One thing to do is use the value of option.equals(...) in the setters:
isSelectedLength.setVisible(option.equals("length"));
isSelectedWeight.setVisible(option.equals("weight"));
isSelectedTemp.setVisible(option.equals("temp"));
isSelectedArea.setVisible(option.equals("area"));
isSelectedTime.setVisible(option.equals("time"));
You could put the nodes in a Map<String, Node> to make the code of the method shorter/less repetitive:
Map<String, Node> nodesByString = new HashMap<>();
nodesByString.put("length", isSelectedLength);
nodesByString.put("weight", isSelectedWeight);
...
private void setIsSelected() {
for (Node n : nodesByString.values()) {
node.setVisible(false);
}
Node visibleNode = nodesByString.get(option);
if (visibleNode != null) {
visibleNode.setVisible(true);
}
}

Return Statements in a Finite State Machine

Could anyone tell me what purpose a return statement in a Finite State Machine's state serves? For example I have this code for a soccer player's state:
public class ChaseBall extends State<FieldPlayer> {
private static ChaseBall instance = new ChaseBall();
private ChaseBall() {
}
//this is a singleton
public static ChaseBall Instance() {
return instance;
}
#Override
public void Enter(FieldPlayer player) {
player.Steering().SeekOn();
}
}
#Override
public void Execute(FieldPlayer player) {
//if the ball is within kicking range the player changes state to KickBall.
if (player.BallWithinKickingRange() && player.isReadyForNextKick()) {
player.GetFSM().ChangeState(KickBall.Instance());
return;
}
//if the player is the closest player to the ball then he should keep
//chasing it
if (player.isClosestTeamMemberToBall()) {
player.Steering().SetTarget(player.Ball().Pos());
return;
}
//if the player is not closest to the ball anymore, he should return back
//to his home region and wait for another opportunity
player.GetFSM().ChangeState(ReturnToHomeRegion.Instance());
}
#Override
public void Exit(FieldPlayer player) {
player.Steering().SeekOff();
}
}
I was wondering if someone could explain what purpose the the return keywords in the first two if statements of the Execute() method serve?
Thanks
In this case it's mainly a formatting alternative to a series of else if clauses. It is logically equivalent to
if (<condition>) {
<code>
} else if (<condition>) {
<code>
} else {
<code>
}

Return random boolean and use to guide an "if" statement

I've been researching how to return a random boolean and then use that returned boolean to drive an "if" statement, but I can't figure out how to structure or what syntax to use.
private Random random;
public void mousePressed(MouseEvent e) {
determineHit();
if (random = true) {
//Perform true//
}
else {
//Perform false//
}
private boolean determineHit() {
return random.nextBoolean();
}
How can I get my determineHit method to return the boolean and then plug that back into the main body of the method?
Thanks
private Random random;
public void mousePressed(MouseEvent e) {
boolean hitResult = determineHit();
if (hitResult) {
//Perform true//
}
else {
//Perform false//
}
private boolean determineHit() {
return random.nextBoolean();
}
Since an if () requires a boolean result, the == true is implied, no need to explicitly code it.
Just make sure that you have instantiated random before using it, in a constructor for example.
if (random.nextBoolean()) {
//Perform true//
} else {
//Perform false//
}

Java generic method to get value of type by using switch on type

I want to have something like this below (example how I would do this in C#), to get typed value from SQLiteDB:
private T GetValueFromDB<T>(String colName) {
object returnValue = null;
switch (typeof(T)) {
case Boolean:
returnValue = dbData.getInt(colName) == 1;
break;
case Int32:
returnValue = dbData.getInt(colName);
break;
case Int64:
returnValue = dbData.getLong(colName);
break;
case String:
returnValue = dbData.getString(colName);
break;
}
return (T)returnValue;
}
Is there a possibility (with switch case or if else) to implement it in Java?
If you already know the type when calling the method, you could do something like this:
private T GetValueFromDB<T>(String colName, Class<T> returnType) {
if(returnType.equals(Boolean.class)) {
return (T)(dbData.getInt(colName) == 1);
} else if(returnType.equals(Int32.class)) {
// and so on
}
}
Java uses type erasure so it is impossible to determine type of T at runtime.
I have made inteface switch, maybe it can be useful for someone :
new ISwitch(pagerCtrl.getPager().getFragmentByID(fragment_id))
.addCase(new ISwitch.CaseListener<Type1>() {
#Override
public void Case(Type1 instance) {
}
}).addCase(new ISwitch.CaseListener<Type2>() {
#Override
public void Case(Type2 instance) {
}
}).addDefault(new ISwitch.DefaultListener() {
#Override
public void Default() {
}
}).build();
public class ISwitch {
public interface CaseListener<T> {
void Case(T instance);
}
public interface DefaultListener {
void Default();
}
Object value;
LinkedList<CaseListener<?>> col = new LinkedList<>();
DefaultListener defaultListener;
public ISwitch(Object value) {
this.value = value;
}
public void build() {
boolean wasNotifiedMinimumOnce = false;
for (CaseListener<?> c : col) {
try {
CaseListener<Object> l = (CaseListener<Object>) c;
l.Case(value);
wasNotifiedMinimumOnce = true;
break;
} catch (ClassCastException e) {
}
}
if ( !wasNotifiedMinimumOnce ) {
if ( defaultListener != null ) {
defaultListener.Default();
}
}
}
public ISwitch addCase(CaseListener<?> caseListener) {
col.add(caseListener);
return this;
}
public ISwitch addDefault(DefaultListener defaultListener) {
this.defaultListener = defaultListener;
return this;
}
}
The small drawback of implementation is that we cant make check instanceof, that why i catch it on cast. For me its not big deal, but it can be performance issue on java server code executed XXXXXX times each seconds.

Categories