Reputation: 13
Ok so in my program I have two classes, LinkPhone.java, and Frame.java. In the LinkPhone part it calls a function to determine if it is true, and then if it is do something. But then I call the function and use an If statement to check it, it recalls the statement from the If statement. Like in the console it says "DEBUG: Frame init success" twice. Why does it call the function twice and how would I fix it?
LinkPhone.java:
Frame.initFrame();
if(Frame.initFrame() == true){
return;
} else {
return;
}
Frame.java:
public static boolean initFrame(){
try {
JFrame frame = new JFrame("Link Phone");
System.out.println("DEBUG: Frame init success");
return true;
} catch (Exception e) {
System.out.println("DEBUG: Frame init failed!!!");
return false;
}
}
Upvotes: 0
Views: 1154
Reputation: 285405
You're calling your method twice!
Frame.initFrame();
if(Frame.initFrame() == true){
return;
} else {
return;
}
Just call it once:
// Frame.initFrame(); // no need for this one
if(Frame.initFrame()){
// hopefully you do more in here!
// return;
} else {
// hopefully you do more in here!
// return;
}
return;
Some side notes:
Upvotes: 4
Reputation: 7032
It's called twice because you write Frame.initFrame()
twice.
Frame.initFrame(); //Once
if(Frame.initFrame() /* Twice */ == true){
return;
} else {
return;
}
If you only meant to call it once and want to store the result, try this:
boolean ok = Frame.initFrame();
if(ok){ //Use result of call
//Do stuff in the event the initting went correctly
return;
} else {
//Do stuff in the event the initting failed
return;
}
Or, event more compactly:
if(Frame.initFrame()){ //Use result of call
//Do stuff in the event the initting went correctly
return;
} else {
//Do stuff in the event the initting failed
return;
}
Upvotes: 0
Reputation: 58848
Yes. Every time your program executes Frame.initFrame()
it calls the method. (That's what the ()
syntax means)
If you want to call it once you can do this (without the extra call before it):
if(Frame.initFrame() == true) {
or this, if you prefer having the method call on a separate line:
boolean result = Frame.initFrame();
if(result == true) {
Upvotes: 0
Reputation: 140299
You need to keep hold of the result from the first time you call the method:
boolean result = Frame.initFrame();
if(result) {
return;
} else {
return;
}
Upvotes: 0