When check if method true, the method is called again? - java

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;
}
}

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:
I would avoid calling a class "Frame" since that would clash with a class that is part of the Java core classes. Give it a more descriptive name to avoid future problems.
It looks like you're calling static methods. This is OK if indicated, but over-use of static methods and variables risks increasing the connectedness of your program, i.e., it can increase code coupling, something that in larger programs can lead to increased complexity and risk of bugs. Java is an OOP language for a reason, since proper use of OOP techniques helps hide data, reducing bugs and increasing code re-use.
Both of your if and else code blocks have a return call. Better to simplify the code and get the return calls out of the blocks. Simply call return after the both blocks.
Again hopefully your if and else blocks hold more code than just matching return statements.

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;
}

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) {

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;
}

Related

Using booleans with set and get methods

To summarize I am making a program for a metro ticket system. and I am using set and get methods for it, when it comes to boolean values (since I need to validate that the person enters enough money for the ticket) how am i supposed to put in the main class( it is defined in brain) using the set method and an if statement.Here is a little fraction of the entire code and the rest is on github(https://github.com/alexxei4/subwayticket). The main is basically the class that will be used for interaction with the user and the brain is where alot of the actions are defined.All help is appreciated, please and thank you.
if (Choice1a == 10){
if(subway1.ticketcounter1(true);){
System.out.println("PRINT SUCCESSFUL, COLLECT YOUR TICKET!");
}
if(subway1.ticketcounter1(false);){
System.out.println("INSEFFICIENT FUNDS, PLEASE ADD MORE");
}
This is not how you evaluate boolean values, you just place the value in an if statement and it will proceed if true and refuse if false, also there is no need to duplicate the statement when you can just place an else block to handle situations that are not true:
if(subway1.ticketcounter1) {
System.out.println("PRINT SUCCESSFUL, COLLECT YOUR TICKET!");
}
else {
System.out.println("INSEFFICIENT FUNDS, PLEASE ADD MORE");
}
Also do not include semicolons in if statements, that's incorrect syntax. Read more about how to use use boolean values here: https://codingbat.com/doc/java-if-boolean-logic.html
EDIT:
After reading through your Github code I see that ticketcounter1 indeed is a method, but what it's doing is trying to change the value of ticketcounter1 like it's a referenced object, but boolean are primitive data types and can't be referenced, and even if they could it still wouldn't work because Java is a pass-by-value language. Read here for more information on that.
public void ticketcounter1(boolean ticketcounter1){
if (credit1 > total1){
ticketcounter1 = true;
}
else {
ticketcounter1 = false;
}
}
public void ticketcounter2(boolean ticketcounter2){
if (credit2 > total2){
ticketcounter2 = true;
}
else {
ticketcounter2= false;
}
Like the other answer said you should be returning the value as boolean instead of trying to change it:
public boolean ticketcounter1(){
if (credit1 > total1){
return true;
}
else {
return false;
}
}
public boolean ticketcounter2(){
if (credit2 > total2){
return true;
}
else {
return false;
}
}
But all in all your code demonstrated fundamental flaws in understanding how the language works, I would suggest picking up a good Java for beginners kind of book or do some introductory online tutorials. Here is a good place to start your learning journey: https://docs.oracle.com/javase/tutorial/java/index.html
You code is like this
public void ticketcounter1(boolean ticketcounter1){
if (credit1 > total1){
ticketcounter1 = true;
}
else {
ticketcounter1 = false;
}
}
public void ticketcounter2(boolean ticketcounter2) {
if (credit2 > total2){
ticketcounter2 = true;
}
else {
ticketcounter2= false;
}
}
It should be like this. Instead of using the variable and passing it though parameter. Use getter. Besides that your code won't run since subway1.ticketcounter1(true) is giving nothing. It is only changing variables stored in Brain.java. No information is being sent to main.
public boolean ticketcounter1(){
if (credit1 > total1){
return true;
}
else {
return false;
}
}
public boolean ticketcounter2(){
if (credit2 > total2){
return true;
}
else {
return false;
}
}
You can create functions without parameters. I don't know what were you trying to do?
if (Choice1a == 10){
if(subway1.ticketcounter1()){
System.out.println("PRINT SUCCESSFUL, COLLECT YOUR TICKET!");
}
if(subway1.ticketcounter1()){
System.out.println("INSEFFICIENT FUNDS, PLEASE ADD MORE");
}
}
subway1.ticketcounter1() will give either true and false. Do not use ; in if statement condition. ; ends the statement. Check this guide to learn about use of semi-colon If you do want to use ; The code should look like this
if (Choice1a == 10){
boolean ticketCounter1 = subway1.ticketcounter1();
if(ticketCounter1){
System.out.println("PRINT SUCCESSFUL, COLLECT YOUR TICKET!");
} else {
System.out.println("INSEFFICIENT FUNDS, PLEASE ADD MORE");
}
}
P.S You don't need two ifs if-else would be better in this case
if(condition) {
// Conditions is true
} else {
// Condition is false
}

How to break inside if condition in java

i Have below method . which i am calling an boolean method inside it.if that boolean method is true then exit from the block else continue with else block. Below is what i tried. but failed to break the method.
public IStatus validate() throws ExecutionValidationException {
ConfigurationHandler handler = new ConfigurationHandler(getExecutionParameters());
if (handler.isModelValidationEnabled()){
//how to handle here and exit here. i need to continue the application
} else
this.loggerStorage.getLogger().info(VALIDATION_DM_START);
try {
return getDataModel().validateModel();
} finally {
this.loggerStorage.getLogger().info(VALIDATION_DM_FINISHED);
}
}
No need to put anything in the if body, the else is skipped if the if is true. But, It would be cleaner to use a boolean negation like,
public void method1(){
A a = new A();
if (!a.method2()) {
method3(); //<-- block not entered if method2() returns true.
}
}
i need to exit from method1()completely. i don't want to continue else
part.How can i break/exit here... and continue with the application.
If false then execute else part
It is the goal of a if else block.
Here if the if statement is true, the else block is never reached.
if(a.method2() == true){
...
}
else{
...
}
You could use a return statement if you had some other processings after the if statement that you don't want ignore in this specific case.
But in this case you don't need to couple the if where you want to make a return with other else if blocks as they are not dependent:
if(a.method2() == true){
...
return;
}
if(...){
...
}
else{
...
}
// do some processing
You can use;
if(a.method2() == true){
return;
}
But I really think you should question what you're trying to accomplish.
public void method1(){
A a = new A();
if(a.method2() == false){
continue with method3();
}
}

How to write short logical expressions in Java?

Is there a way to make consecutive logical operations on the same variable shorter?
Example:
if (animation.getStatus() == Animation.Status.PAUSED || animation.getStatus() == Animation.Status.STOPPED) {
animation.playFromStart();
} else if (animation.getStatus() == Animation.Status.RUNNING) {
animation.stop();
}
You see in the if-clause that there I check the animation.getStatus() twice, once for paused and once for stopped.
Is there a way to make it like animation.getStatus() == Animation.Status.PAUSED || Animation.Status.STOPPED?
I'm sure this question has been asked already but I really don't know what to search for, so I'm sorry if this is a duplicate.
No; Java syntax is immutable.
There are several options, but the easiest is to refactor, which as a bonus makes it legible, e.g.,
if (animation.shouldReplay()) {
animation.playFromStart();
} else if (animation.shouldStop() {
animation.stop();
}
Or a level deeper, e.g.,
animation.controlFromCurrentStatus();
If you're unwilling to encapsulate, simply importing the statuses helps:
Animation.Status currentStatus = animation.getStatus();
if (currentStatus == PAUSED || currentStatus == STOPPED) {
animation.playFromStart();
} else if (currentStatus == RUNNING) {
animation.stop();
}
Or make them enums, which arguably they should be anyway:
switch (currentStatus) {
case PAUSED:
case STOPPED:
animation.playFromStart();
break;
case RUNNING:
animation.stop();
}
In this case switch statement would look nice
switch (animation.getStatus()) {
case Animation.Status.PAUSED:
case Animation.Status.STOPPED:
animation.playFromStart();
break;
case Animation.Status.RUNNING:
animation.stop();
break;
}
You can do it in a couple of ways:
By introducing a temporary variable - make a variable, assign the status to it, and use the value of the variable in the expressions instead of making the call multiple times
By writing a helper method - write a method that takes the current status and a variable argument list of statuses, and call this method in the conditional.
Here is the illustration to the first way of doing it:
Animation.Status status = animation.getStatus();
if (status == Animation.Status.PAUSED || status == Animation.Status.STOPPED) {
animation.playFromStart();
} else if (status == Animation.Status.RUNNING) {
animation.stop();
}
Here is an illustration to the second way of doing it:
private static boolean checkStatus(Animation.Status status, Animation.Status... expected) {
for (Animation.Status e : expected) {
if (e == status) {
return true;
}
}
return false;
}
...
if (checkStatus(animation.getStatus(), Animation.Status.PAUSED, Animation.Status.STOPPED)) {
...
}
If your code is multithreaded, which it probably should be if you're running animations and want to be able to stop/start/pause them, then you should consider synchronization.
So to take Dave Newtons code snippet and make it thread-safe:
synchronized(this){
if (animation.shouldReplay()) {
animation.playFromStart();
} else if (animation.shouldStop() {
animation.stop();
}
}
Thus, there is no danger the first condition will return false, then the current thread is no longer Running, another thread modifies the status of the animation, then the current thread again becomes Runnable and tries to stop the animation.

Java - How to identify whether a method executed completely or Returned

Is there a way to identify whether the following method executed completely or returned halfway through(i.e at line no 3)
static int a=0;
static void test(){
if(a>10){
return;
}
a++;
}
The method was invoked by another method.(a might have been changed by it)
I cannot change the method declaration. I am dealing with an object I created from a java file created by someone else. I am not allowed to change the original file
Your method does almost nothing and no there is no way in this example you gave to know if the method returned before complete execution but if you willing to change the function to a boolean type you can return true at complete execution and false at incomplete.
static boolean test()
{
if(a>10)
return false;
a++;
return true;
}
Run the code under debugger like jdb and set the breakpoint on the internal return statement. If the program stops at this breakpoint, this obviously means that it would return through that statement.
To make things more automated, you could try to launch the debugger and control the debugger from a Java program through Runtime. This would make the approach applicable for more use cases, while not for all.
You could use
void test(int a) {
if (a > 10) {
return;
}
a++;
System.out.println("test executed completely!");
}
Or if you want to use the information programmatically
private boolean executedCompletely;
void test(int a) {
executedCompletely = false;
if (a > 10) {
return;
}
a++;
executedCompletely = true;
}
When you use your test method, you can check whether it ran completely this way:
int initialA = a;
test();
int finalA = a;
if (finalA != initialA) {
//a has been changed, therefore the method ran completely
} else {
//a has not been changed, therefore it was not incremented, therefore the method did not run completely
}

Syntax error on else

Got probably a simple problem but where ever I google it it seems the problem
is a semicolon at the end of the if statement, the problem is eclipse giving me the syntax error asking to delete my else on the else if statement, this happens nearly all the time for me and i end up using multiple IF's.
if(saleStatus == false || offerPrice <= currentOffer)
{
System.out.print("Error, sale is not open");
return false;
}
else if(currentOffer >= reservePrice)
{
saleStatus = false;
}
Every path your function can take must return a value, if you specify that it will return something.
In this case, you have probably specified it as
access_modifier boolean function_name(params){
... // ^return type
}
So, all code paths must return a boolean.
In your code, if it takes the else... path, and exits without returning anything, that isn't permitted.
else if(currentOffer >= reservePrice)
{
saleStatus = false;
//return something here (null if you don't care)
}
//or return something here (which all code-paths hit)
If you use an IDE like Eclipse, it can warn you in advance about things like this.
There's no return statement in your else block. If a return type is declared in your method, the method would not know what to return if the code enters the else block.
Put one in it or after (*).
In the first if, you return a value, so there is no point on specifying "else" because the rest of the method is not executed.
Some developers avoid multiple return statements in functions for code quality.
I wrapped your code in a class declaration, with minimum additional declarations, and a return after the whole if-else structure, and Eclipse shows no errors. I suggest writing a similarly minimal complete program that does show the problem, and posting it.
You do not need "else if" rather than "if" for the second test, but it should be harmless.
public class Bad {
boolean saleStatus;
int offerPrice;
int currentOffer;
int reservePrice;
public boolean problem() {
if(saleStatus == false || offerPrice <= currentOffer)
{
System.out.print("Error, sale is not open");
return false;
}
else if(currentOffer >= reservePrice)
{
saleStatus = false;
}
return true;
}
}

Categories

Resources