Using booleans with set and get methods - java

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
}

Related

How to stop actor from continuously picking up object?

I'm taking an intro to java class at school and were doing very early on stuff. We are given a few methods and the knowledge of how if else statements, while loops, etc work. We use a program called greenfoot. The objective of the project is to have the character go around and pick up all the leaves, then place them at the end of the row and repeat. The order is changed so you need control statements. I am encountering an issue where at the end of each row, I will place a leaf, then pick it up and loop that forever. I have tried to solve it with variables to no avail. My code is here:
public void rowSweep() {
boolean turnCheck = false;
boolean leafCheck = true;
if (foundLeaf() && (leafCheck)) {
pickLeaf();
leafCheck = true;
}
else if (canMove() && (!facingNorth())) {
walk();
leafCheck = true;
}
else if (hasLeaf()) {
while (hasLeaf()) {
placeLeaf();
leafCheck = false;
}
}
else {
turnLeft();
while (canMove() && (!facingNorth())) {
walk();
turnCheck = true;
}
if (!canMove() && (turnCheck)) {
turnLeft();
walk();
turnLeft();
}
}
}
There are no syntax errors, just it doesn't do it properly. How can I make it so that I can move on after I place it instead of infinitely repeating?

Using a variable that is changed within an if statement

I am writing a program in JAVA where I need to change a boolean, but I am not able to fix it.
The lay out is as follows
while(statement){
Boolean behind = true;
if (behind == true){
do something
behind = false;
}
if (behind == false){
do something else
behind = true;
}
}
So basically my program needs to iterate 'doing something' and 'doing something else'. But I reckon my boolean behind is not changed by the if-statement, since that 'version' of behind only lives within the statement. Any suggestions on how to cope with this?
Do not use var == true/false. This may reduce performance and makes the code unclear. Use var instead of var == true and !var instead of var == false.
Use an else statement instead of checking the condition's opposite.
if (behind) {
//...
behind = false;
} else {
//...
behind = true;
}
3. **Define the boolean outside `while`.**
This also solves your problem because you don't "re-check" the variable.
Boolean behind = true;
while(statement){
if (behind){
do something;
behind = false;
}else{
do something else;
behind = true;
}
}
Define the boolean before the while block.
Boolean behind = true;
while(statement){
if (behind){
do something;
behind = false;
} else {
do something;
behind = true;
}
}

The corresponding then clause does not complete normally

Given a simple if statement in the form
public static String test(boolean flag) {
if (!flag) {
return "no";
} else {
System.out.println("flag enabled");
}
return "yes";
}
or
public static String test(final boolean flag)
{
if (flag)
{
System.out.println("flag enabled");
return "yes";
}
else
{
return "no";
}
}
Eclipse gives me the warning, underlining the whole else block
Statement unnecessarily nested within else clause. The corresponding then clause does not complete normally
However, this...
public static String test(final boolean flag)
{
if (flag)
{
System.out.println("flag enabled");
return "yes";
}
return "no";
}
does not give the warning.
this question seems related, but I'm not using return in the else of the first example, and else is not finally.
I understand that this is simply a preference, and that it can be turned off. However, I don't like ignoring things simply because I don't understand what is the problem. And I can't seem to find any documentation on why Eclipse added this as a configurable warning.
So in all, What does The corresponding then clause does not complete normally mean? What is the problem that this warning is trying to protect me from?
You can remove the else clause and that will remove the warning.
To answer your other question, "The corresponding then clause does not complete normally" is referring to the fact that the "then" clause has a return statement. Completing "normally" means control flow continues to the statements after the "else" block, but this doesn't happen since you returned.
There is no logical, functional, or runtime difference between:
// Gets warning
public static String test(final boolean flag) {
if (flag) {
System.out.println("flag enabled");
return "yes";
} else {
return "no";
}
}
and
// Doesn't get warning
public static String test(final boolean flag) {
if (flag) {
System.out.println("flag enabled");
return "yes";
}
return "no";
}
So it boils down to a style preference. Why might Eclipse think this is worth a warning? Think of it as similar to "unreachable code" -- an aspect of the code is unnecessarily (and perhaps unusually) verbose, and this usually merits another look to ensure that no logic errors are hiding. If I wrote the first code snippet and got the warning, I'd be thankful for Eclipse and happily improve the code, arriving at the second snippet. But again, that's just because I prefer the second snippet.
Here's a scenario where this might come into play and affect functionality (unintentionally). Suppose the code originally looks like this:
// Returns true if the dog was fed
boolean feedDog(Dog dog) {
if (!dog.isHungry()) {
return false;
}
Food food;
if (dog.isBadToday()) {
food = getDefaultFood();
} else {
food = getTreat();
}
dog.feed(food);
return true;
}
Sometime later, the team decides that feedDog should only return true if the dog was fed a treat. What if the code is modified to:
// Returns true if the dog was fed *a treat*
boolean feedDog(Dog dog) {
if (!dog.isHungry()) {
return false;
}
Food food;
if (dog.isBadToday()) {
food = getDefaultFood();
return false; // Dog wasn't fed a treat
} else {
food = getTreat();
}
dog.feed(food);
return true;
}
Now there's a bug because the programmer went with the shortest change that "looked right at first glance" -- the poor dog doesn't get fed if it misbehaved. Eclipse's warning is saving the dog here, telling the programmer to pay attention to the logic surrounding the if statement, which doesn't seem right anymore (according to Eclipse). Hopefully the programmer will heed the warning and avoid returning from the if block:
// Returns true if the dog was fed *a treat*
boolean feedDog(Dog dog) {
if (!dog.isHungry()) {
return false;
}
Food food;
boolean fedTreat = false;
if (dog.isBadToday()) {
food = getDefaultFood();
} else {
food = getTreat();
fedTreat = true;
}
dog.feed(food);
return fedTreat;
}

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

When does Java if statement exit?

I have a function when has an if-else statement. It essentially looks like this:
if(boolean == true)
{
// do something
boolean = false;
}
else if(boolean == false)
{
// do the other thing
boolean = true;
}
Now, my understanding is that the if statement will exit and return control to the function and then continue according to the changed boolean value. But I'm clearly missing something because my code is not exiting the original 'if'/'else if' statement (whichever the original case). Can anyone tell me what I've missed?
Well as requested, additional data about the code is that it is a part of my android project and each condition in the if-else block has a nested function and the boolean(global) value is being set/unset withing these functions. So the code now looks like this:
dummyFunction(){
boolean = checkIfTrueOrFalse();
if (boolean) {
onClick( public void onClick(){
// do something
boolean = false;}
} else if(boolean == false){
onClick( public void onClick(){
// do something
boolean = true;}
}
}
Any ideas?
if(boolean == true)
{
// do something
boolean = false;
}
if (boolean == false)
{
// do the other thing
boolean = true;
}
When you do this, then the program will flow to the second condition. In an if/else if statement, if the if statement has been satisfied, then the program will ignore the else if block.
Your current code simply flows through the first if block and then skips the else if statement to end the block.
void someMethod()
{
boolean aBoolean = true;
if(aBoolean == true)
{
// do something
aBoolean = false;
}
else if(aBoolean == false)
{
// do the other thing
aBoolean = true;
}
}
When someMethod will execute, since aBoolean is assigned with true, control will come to if block cause the condition becomes true. if it was false, then the control will come to else part.
We have many good answers/comments already but just wanted to add something here -
1.
if (condition) {
} else {
}
is a single code construct. The condition will be evaluated at the beginning at run time and java will decide which block to execute i.e. the if block or the else block. Only 1 of the 2 can be executed.
Java allows us to nest if/else. That means we can have something like below -
if(condition1){
} else if (condition2) {
} else if (condition3) {
} else {
}
It is effectively same as below -
if (condition1) {
} else {
if (condition2) {
} else {
if (condition 3) {
} else {
}
}
}
Here, it should be noted that only the block which satisfies the condition will be executed. If none of the conditions is met, then the inner most else will be executed (i.e. the else block of condition3 )
Finally, I feel that your confusion is between the below blocks
boolean aBoolean = true;
if(aBoolean == true)
{
// do something
aBoolean = false;
} else if(aBoolean == false)
{
// do the other thing
aBoolean = true;
}
VS
boolean aBoolean = true;
if(aBoolean == true)
{
// do something
aBoolean = false;
}
if(aBoolean == false)
{
// do the other thing
aBoolean = true;
}
In the latter of the 2 examples, there are 2 independent if blocks and both will get executed (off course, this is not logically correct but it is a legal java code.)
Could you provide more info regarding your code not exiting either of the 2 blocks? Doing System.out.println() of variables within your blocks might be able to help you determine why your code is not exiting.
You could use an if/else pair instead of an if/else-if as the parameter that your code depends on is would be either true/false. If the if-block is not satisfied, automatically the else-block would be traversed.
Your code is actually a shortcut for
if (boolean) {
// do something
boolean = false;
} else {
if (!boolean) {
// do the other thing
boolean = true;
}
}
Written this way, it maybe becomes clearer that the inner if nested in the else case will not be processed if the first if condition was already met.
Well I've solved it (taking inputs from here of course). I just added a call to the function within the nested functions and it worked. Now the code looks like this:
public static void dummyFunction(){
boolean = checkIfTrueOrFalse();
if (boolean) {
onClick( public void onClick(){
// do something
dummyFunction();
boolean = false;}
} else if(boolean == false){
onClick( public void onClick(){
// do something
dummyFunction();
boolean = true;}
}
}

Categories

Resources