I created a while loop which i want to stop when it becomes true
so i put:
while(!vending1.cansEmpty()) {
vending1.clickCan();
count++;
}
now it has been set so that the vending machine has 10 cans inside
and every time you call the method clickCan() it minus's 1 can,
but the while loop doesn't end when it the machine is empty (method becomes true), it just goes on infinitly
I am not sure why though
public class VendingMachine(){
private Integer cans;
public VendingMachine(int numCans) {
this.cans = numCans
}
public void clickCan() {
cans--;
}
public boolean cansEmpty() {
if (cans <= 0) {
return true;
} else {
return false;
}
}
}
I think you just need to make sure that your cans empty function returns a boolean.
Related
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?
This is a simple program to check if a number if Fibonnacci. I have a mysterious bug: the "return true" statement isn't triggered. Instead, "hi" will be printed many times. Return should break out of the method, does anyone have insight as to why it's not? Thanks!
import java.util.*;
public class Solution {
public static boolean listFibs (long oldestFib, long oldFib, long input) {
long newFib = oldestFib + oldFib;
while (newFib < Math.pow(10,10)) {
if (newFib == input) {
System.out.println("hi");
return true;
}
listFibs(oldFib, newFib, input);
}
return false;
}
public static void main(String[] args) {
/*Scanner in = new Scanner(System.in);
int testCases = in.nextInt();
for (int i = 0; i < testCases; i++) {
int a = in.nextInt();
System.out.println("A= " + a);
System.out.println(listFibs(0, 1, a));
}*/
System.out.println(listFibs(0, 1, 5));
}
}
Due to the recursion there are many incarnations of listFibs. The return just leaves one of them.
In the example given, you get the following calls:
listFib(0,1,5)
listFib(1,1,5)
listFib(1,2,5)
listFib(2,3,5)
-> true
listFib(2,3,5) // called again due to the loop
-> true
listFib(2,3,5) // called again due to the loop
-> true
listFib(2,3,5) // called again due to the loop
-> true
listFib(2,3,5) // called again due to the loop
...
actually, if "hi" is printed many times, the return statement must be executed the same time. if you install a break point in that return statement, you will see.
your function is a recursion, and "listFibs" will be called many times.
Print values of all 3 variables in the method and you will know what's wrong. You are using recursion, see how many times it's being called.
Also, after call to listFib, execution will go to while loop again. You need to say return listFibs at least. Between your listFibs and while loop condition, nothing is changing. 2,3,5 are being found again and again.
see http://ideone.com/1d440f
You are one step short... The recursive call doesn't do anything with the results you get from listFibs, so the program sees something like this:
while (newFib < Math.pow(10,10)) {
if (newFib == input) {
System.out.println("hi");
return true;
}
true //or false
}
Try adding this extra little IF statement. Once a true result is found it will be passed back up the chain and out of the function.
while (newFib < Math.pow(10,10)) {
if (newFib == input) {
System.out.println("hi");
return true;
}
if listFibs(oldFib, newFib, input){
return true;
}
}
Ok, so I am going to see if this makes sense. In the second method below (int numAdd) I want to be used for the private method (int searchingNum). I don't really understand how private methods work, but whatever number the user enters for the (int numAdd) I want to be duplicated for the parameters in the first method. How is this possible?
//See if user input returns -1 to test whether or not number exists in the array
private int indexOf(int searchingNum)
{
}
//Add number in the array
public boolean addNumber(int numAdd)
{
if (list.contains(numAdd))
{
return false;
}
else
{
list.add(numAdd);
count++;
return true;
}
}
that's it? indexOf(numAdd);
public boolean addNumber(int numAdd)
{
// somewhere, in the middle of nowhere
indexOf(numAdd);
// more of code
}
You can call method of same class directly. No need to do anything. Like this :
public boolean addNumber(int numAdd)
{
int abc = indexOf(numAdd);
//Whatever you want to do...
}
Why isn't this structure acceptable? Anyway it returns a boolean value right??
public boolean a()
{
if(condition)
{
if(condition)
{
if(condition)
{
return true;
}
}
}
}
It's not valid because there is a possibilty where nothing is returned. Your method is declared as returning a boolean value, so it MUST return a boolean value at some point in the code before the method is finished, regardless of the inner logic. If your if-statement if (condition) is false, the method doesn't have another return statement, so the code won't even compile. To fix this, add a "default" return value:
public boolean a()
{
if(condition)
{
if(condition)
{
if(condition)
{
return true;
}
}
}
return false;
}
Not valid because you need to do a return some default value (return) .
What if conditions not satisfied ??
valid is :
public boolean a()
{
if(condition)
{
if(condition)
{
if(condition)
{
return true;
}
}
}
return false;
}
As a side note,To make your code mode readable,I suggest
if(condition && condition && condition)
{
return true;
}
return false;
Prefer to read jls-14.17
Though the method returns true when the condition is satisfied, it doesn't specify a return value when the condition isn't satisfied. The method should cover all the code paths (read conditional statements).
As the answers above correctly state, you absolutely have to return something in Java. C doesn't really care.
In order to avoid this I would recommend decreasing the level of nesting to do something like
boolean value=false; //default return
if(cond && cond)
return value;
if(cond)
return false; //if you want to be more specific
if(cond)
value=true;
return value;
so a value gets returned no matter what. On the plus side, readability increases
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;}
}
}