Boolean not being returned? - java

New Developer here, I am doing a practice challenge that should return either true or false depending on if a dog is barking and what time it is in the day.
public class BarkingDog {
public static boolean bark(boolean barking, int hourOfDay){
if(barking=true) {
if (hourOfDay < 8 || hourOfDay > 22) {
return true;
} else if (hourOfDay < 0 || hourOfDay > 23) {
return false;
} else {
return false;
}
}
else{
return false;
}
}
public static void main(String args[]){
bark(true,1);
}
}

try it now..
the first thing that was wrong is the IF statement..
since you should use == not = alone in it.
secondly you should print the answer just to know what really happened.
public class BarkingDog {
public static boolean bark(boolean barking, int hourOfDay){
if(barking==true) {
if (hourOfDay < 8 || hourOfDay > 22) {
return true;
} else if (hourOfDay < 0 || hourOfDay > 23) {
return false;
} else {
return false;
}
}
else{
return false;
}
}
public static void main(String args[]){
System.out.println(bark(true,1));
}
}

another small hint: instead of if(barking=true) you can just write if(barking)

public class BarkingDog {
public static boolean bark(boolean barking, int hourOfDay){
if(barking==true) {
if (hourOfDay < 8 || hourOfDay > 22) {
return true;
} else if (hourOfDay < 0 || hourOfDay > 23) {
return false;
} else {
return false;
}
}
else{
return false;
}
}
public static void main(String args[]){
System.out.println(bark(true,1));
}
}
You are using '=' to check the condition but it use to assign the value.example
int a = 1;
Use '==' to check the condition.

you can and you should simplify this code.there is nonsense if condition...write code like this :
public static boolean bark(boolean barking, int hourOfDay){
if(barking) {
if (hourOfDay < 8 || hourOfDay > 22) {
return true;
else {
return false;
}
}
else{
return false;
}
}
public static void main(String args[]){
//this is static values and you can get this values dynamic i.e from server
boolean result = bark(true, 1);
System.out.println(result);
}
}

when i run it i don't get anything in return.
Because, if a method has a return type(it is returning a value), try to hold this value in same type as the return type in a variable, if you don't assign method invocation to a variable it will be ignored.
boolean result = bark(true, 1);
System.out.println(result);

Related

NumberVerify: missing return statement

import static java.lang.System.*;
public class NumberVerify
{
public static boolean isOdd( int num )
{
if((num%2)==0)
{
boolean yes = true;
return true;
}
}
public static boolean isEven( int num )
{
if((num%2)!=0)
{
boolean yes = false;
return false;
}
}
}
The error messages say "missing return statements" on the }'s.
I tried adding
return true;
after the set of braces nested by
if((num%2)==0)
and did something similar with the
if((num%2!=0)
nest, although with
return false;
That only caused the isOdd to pop up as true and isEven to pop up as false regardless of the inputted number itself.
Here is the runner program.
import static java.lang.System.*;
import java.util.Scanner;
public class NumberVerifyRunner
{
public static void main ( String[] args )
{
//add in input
System.out.println("5 is odd :: " + NumberVerify.isOdd(5));
System.out.println("5 is even :: " + NumberVerify.isEven(5));
System.out.println("0 is odd :: " + NumberVerify.isOdd(0));
System.out.println("0 is even :: " + NumberVerify.isEven(0));
System.out.println("2 is odd :: " + NumberVerify.isOdd(2));
System.out.println("2 is even :: " + NumberVerify.isEven(2));
//add in more test cases
}
}
How do I fix the missing return statements in the NumberVerify class?
You need to return a value if the 'if' clause is not satisfied.
All code blocks need to return a value. This solution should work well.
public static boolean isOdd(int num) {
if ((num % 2) == 0) {
return true;
} else {
return false;
}
}
public static boolean isEven(int num) {
if ((num % 2) != 0) {
return false;
} else {
return true;
}
}
Try adding return false after the first if statement and return true after the second.
Also you could just return the result of num%2==0 without the if statement due to the fact that num%2==0 is a boolean value. So you could also delete the if statements and do return( num%2)==0;
For the other one do return (num%2 )!=0;
isOdd and isEven must return boolean for all branches.
This will work
import static java.lang.System.*;
public class NumberVerify
{
public static boolean isOdd( int num )
{
return numr%2 == 1;
}
public static boolean isEven( int num )
{
return num % 2 == 0;
}
}
In java your return statement is the last statement. In your case just change whit following code
import static java.lang.System.*;
public class NumberVerify
{
public static boolean isOdd(int num)
{
if(num%2 == 0)
{
return true;
}
return false;
}
public static boolean isEven( int num )
{
if(num%2 !=0 )
{
return true;
}
return false;
}
}
import static java.lang.System.*;
public class NumberVerify
{
public static boolean isOdd( int num )
{
if((num%2)!=0)
{
boolean yes = true;
}
return yes;
}
public static boolean isEven( int num )
{
if((num%2)==0)
{
boolean yes = true;
}
return yes;
}
}
Your code have the return statement is out of the scope.
Method signature have return the boolean value but you put return statement if() control scope only so you change the public scope(current method scope).
Your All code path will not return values:
Consider your code :
public static boolean isOdd( int num )//Assume num as 7
{
if((num%2)==0)// 7 % 2 will be 1 , condition fails
{
boolean yes = true;
return true;// this statement won't be executed
}
// you have no return statement here
}
import static java.lang.System.*;
public class NumberVerify
{
public static boolean isOdd( int num )
{
boolean isOddNumber = (num %2 ) !=0
return isOddNumber;
}
public static boolean isEven( int num )
{
boolean isEvenNumber = (num %2 )==0
return isEvenNumber;
}
}
you give a return to a if and forgot the else. In your method isOdd() the return is only in the if not in the method. you may change your code like this.
public static boolean isOdd( int num )
{
if((num%2)==0)
{
boolean yes = true;
return true;
} else {// you must add the else
return true;// return a boolean value here.true or false,it's up to you.
}
// Or add a return below without add the else.
return ture;// true or false,it's up to you.
}
public static boolean isEven( int num )
{
if((num%2)!=0)
{
boolean yes = false;
return false;
} else {// you must add the else
return true;// return a boolean value here.true or false,it's up to you.
}
// Or add a return below without add the else.
return ture;// true or false,it's up to you.
}

Exception in thread "main" java.lang.NullPointerException virtual stack class

I am trying to use this class to evaluate postfix expressions and when testing it am thrown this exception at line 32 where the virtual stack should push.
public class PostfixEval
{
private IntStack s;
public PostfixEval()
{
IntStack s = new IntStack();
}
public boolean isInteger(String s)
{
int i = 0;
boolean isDigit = true;
while(i < s.length() && isDigit)
{
isDigit = s.charAt(i) >= '0' && s.charAt(i) <= '9';
i++;
}
return isDigit;
}
public int eval(String e)
{
String[] tokens = e.split("\\s+");
for(int i=0; i<tokens.length; i++)
{
if(isInteger(tokens[i]))
{
s.push(Integer.parseInt(tokens[i]));
}
else
{
int a,b,c;
b = s.pop();
a = s.pop();
c = 0;
char d = tokens[i].charAt(0);
if(d == '+')
{
c = a + b;
}
else if(d == '-')
{
c = a - b;
}
else if(d == '*')
{
c = a*b;
}
else if(d == '/')
{
c = a/b;
}
else if(d == '%')
{
c = a%b;
}
else
{
System.out.println("Error");
System.exit(0);
}
s.push(c);
}
}
return s.peek();
}
}
I have used jgrasp to see what Integer.parseInt(tokens[i])) evaluates to and confirm it is a number from the split string. When trying to push a number that I type into the paramater of the push method it works, so why do I get null exception when using the PostfixEval to push?
Here is my stack class.
public class IntStack implements StackIntADT
{
// fields
private int[] stk;
private int sp;
// constructors
public IntStack()
{
sp = -1;
stk = new int[10];
}
public IntStack( int s )
{
sp = -1;
stk = new int[s];
}
// stack class methods
public void push(int element)
{
if(!isFull())
{
sp++;
stk[sp]=element;
}
else
{
System.out.println("Element" + element);
System.exit(0);
}
}
public int pop()
{
int rv = 0;
if(!isEmpty())
{
rv = stk[sp--];
}
else
{
System.out.println(rv);
System.exit(0);
}
return rv;
}
public int peek()
{
return stk[sp];
}
public boolean isEmpty()
{
return sp==-1;
}
public boolean isFull()
{
return sp==stk.length-1;
}
public int size()
{
return stk.length;
}
public String toString()
{
String s = "";
for(int x=0;x<10;x++)
{
s = s + " " + stk[x];
}
return s;
}
}
The constructor should not define a local s variable (which hides the member variable with the same name). The member variable is never assigned a value.
Change the constructor to this:
public PostfixEval() {
s = new IntStack();
}

Counter: decrease method disregards boolean

I am trying to create a counter that holds a number that can be increased and decreased. The program also has a boolean check: when true, the counter cannot go negative. The program seems to run fine, but I cannot get the decrease methods (both decrease by one and decrease by input) to get the boolean right. It does not check the boolean value or something? I am new to Java and need help understanding what is wrong. The class is as follows:
public class Counter {
private int value;
private boolean check;
public Counter(int startingValue, boolean check) {
if (this.check = true) {
this.value = startingValue;
if (value < 0) {
value = 0;
}
}
if (this.check = false) {
this.value = startingValue;
}
}
public Counter(int startingValue) {
this.check = false;
this.value = startingValue;
}
public Counter(boolean check) {
this.check = check;
}
public Counter() {
this.value = 0;
this.check = false;
}
public int value() {
return this.value;
}
public void increase() {
value++;
}
public void decrease() {
if (this.check == true) {
this.value--;
if (value < 0) {
value = 0;
}
} else if (this.check == false) {
this.value--;
}
}
public void increase(int IncreaseAmount) {
if (IncreaseAmount >= 0) {
this.value = value + IncreaseAmount;
}
}
public void decrease(int DecreaseAmount) {
if (DecreaseAmount >= 0) {
this.value = value - DecreaseAmount;
}
if (check == true && value < 0) {
value = 0;
}
}
}
Now, if I was to execute a main program with this class like this for example:
Counter count = new Counter (2, true);
count.decrease();
count.decrease();
count.decrease();
What I want my program to do is to not go negative since the boolean check is true. Yet it does go to -1. Why is this?
You fail to set the global variable check to false. You also used = instead of ==:
use:
public Counter(int startingValue, boolean check) {
this.check = check;
if (check == true) {
value = startingValue;
if (value < 0) {
value = 0;
}
}
else {
value = startingValue;
}
}
You need to use == to compare equality. The use of a single = sets the value.
Better yet, when checking the value of a boolean, just use the boolean. So instead of
if (someBool == true)
prefer
if (someBool)
Similarly, instead of
if (someBool == false)
prefer
if (!someBool)
Your boolean tests in your if statements need to use == for equality comparison in your constructor.
In your constructor's second if statement, you are assigning check to false.
When performing boolean logic with a boolean, just use the boolean.
So instead of
"if (this.check == true)" do "if (this.check)"
and
"if (this.check == false)" do "if (!this.check)"
Also, you had "if (this.check = true)" for some, which assigns true to this.check.
You main issue is that you missed an assignment of an method parameter to the object variable "this.check = check; // I added this"
Compare your version with this:
public class Counter {
private int value;
private boolean check;
public Counter(int startingValue, boolean check) {
this.check = check; // I added this
if (this.check) { //I changed this
this.value = startingValue;
if (value < 0) {
value = 0;
}
} else { //and this
this.value = startingValue;
}
}
public Counter(int startingValue) {
this.check = false;
this.value = startingValue;
}
public Counter(boolean check) {
this.check = check;
}
public Counter() {
this.value = 0;
this.check = false;
}
public int value() { //good practice to use getVar and setVar, ie: getValue()
return this.value;
}
public void increase() {
value++;
}
public void decrease() {
if (this.check) { // you are not consistent with this.value VS value, which can be a confusing practise
this.value--;
if (value < 0) {
value = 0;
}
} else {
this.value--;
}
}
public void increase(int increaseAmount) { //you had "IncreaseAmount", good practice to start vars with lower case
if (increaseAmount >= 0) {
this.value = + increaseAmount;
}
}
public void decrease(int decreaseAmount) {
if (decreaseAmount >= 0) {
this.value = value - decreaseAmount;
}
if (check && (value < 0)) {
value = 0;
}
}
public void print(){
System.out.println("value:"+value+" check:"+check);
}
public static void main(String[] args) {
Counter count = new Counter (2, true);
count.decrease();
count.print();
count.decrease();
count.print();
count.decrease();
count.print();
}
}

Having problems with my Card Game in java

This is my code, my questions is with my deal method, how do I get it to inclement the to a different number every time I call it and also how to create a Boolean method. This is my code, my questions is with my deal method, how do I get it to inclement the to a different number every time I call it and also how to create a Boolean method.
package Card;
import java.util.Random;
/**
*
* #author Mr. Pierre
*/
public class Card {
private int SuitRank;
private int CardRank;
private String cardValue;
//My constructor
public Card()
{
SuitRank=1;
CardRank=2;
}
//My deal method
void dealCard()
{
SuitRank++;
Random randomGenerator = new Random();
int SuitRank = randomGenerator.nextInt(4)+1;
CardRank++;
Random randomGenerator1 = new Random();
int CardRank= randomGenerator1.nextInt(13)+2;
}
//My compare method
public int compare(Card otherCard)
{
if (otherCard.getCardRank() > CardRank)
return 1;
if (otherCard.getCardRank() == CardRank)
{
if (otherCard.getSuitRank() > SuitRank)
return 1;
if (otherCard.getSuitRank()< SuitRank)
return -1;
if (otherCard.getSuitRank()==SuitRank)
return 0;
}
if (otherCard.getCardRank() < CardRank)
return -1;
return CardRank;
}
//my Get suitrank method
public int getSuitRank()
{
SuitRank++;
return SuitRank;
}
public String getSuitName ()
{
String SuitName="";
if( SuitRank == 1){
SuitName = "Clubs";
}
else if(SuitRank == 2){
SuitName = "Diamonds";
}
else if(SuitRank == 3){
SuitName = "Hearts";
}
else if(SuitRank == 4){
SuitName = "Spades";
}
return SuitName;
}
public int getCardRank ()
{
return CardRank;
}
public String getCardName ()
{
String CardName="";
if(CardRank==2){
CardName="Duce";
}
else if(CardRank==3){
CardName="Three";
}
else if(CardRank==3){
CardName="Three";
}
else if(CardRank==4){
CardName="Four";
}
else if(CardRank==5){
CardName="Five";
}
else if(CardRank==6){
CardName="Six";
}
else if(CardRank==7){
CardName="Seven";
}
else if(CardRank==8){
CardName="Eight";
}
else if(CardRank==9){
CardName="Nine";
}
else if(CardRank==10){
CardName="Ten";
}
else if(CardRank==11){
CardName="Jack";
}
else if(CardRank==12){
CardName="Queen";
}
else if(CardRank==13){
CardName="King";
}
else if(CardRank==14){
CardName="Ace";
}
return CardName;
}
public String toString()
{
return getCardName()+ " of " +getSuitName();
}
}
int SuitRank = randomGenerator.nextInt(4)+1;
The int means you're creating a local variable instead of modyfying a class member. Also, why are you calling SuitRank++ if you're planning to set SuitRank to a random value right away? Same applies to CardRank.
As for the Boolean method - it's just public Boolean method(...).

Having trouble with java class methods

ok so my assignment I'm supposed to write a class that stores a temperature that the user gives and checks it with the set parameters to see if Ethy/Oxygen/Water are either freezing or boiling and then display it at the end which ones will be freezing/boiling at the temperature that they entered. I have the majority of both the class and tester completed but I'm getting several errors on my code. I'm not asking anyone to give me the answer but if you could tell me what I'm doing wrong I would greatly appreciate it. Here is my code for class:
public class FreezingBoilingPoints {
private int temperature;
public FreezingBoilingPoints(int temp) {
temperature = temp;
}
public void setTemperature(int temp) {
temperature = temp;
}
public int getTemperature() {
return temperature;
}
private Boolean isEthylFreezing(int temperature) {
if (temperature <= -173) {
return true;
} else {
return false;
}
}
private Boolean isEthylBoiling(int temperature) {
if (temperature >= 172) {
return true;
} else {
return false;
}
}
private Boolean isOxygenFreezing(int temperature) {
if (temperature <= -362) {
return true;
} else {
return false;
}
}
private Boolean isOxygenBoiling(int temperature) {
if (temperature >= -306) {
return true;
} else {
return false;
}
}
private Boolean isWaterFreezing(int temperature) {
if (temperature <= 32) {
return true;
} else {
return false;
}
}
private Boolean isWaterBoiling(int temperature) {
if (temperature >= 212) {
return true;
} else {
return false;
}
}
public String showTempinfo() {
if (isEthylFreezing()) {
System.out.println("Ethyl will freeze");
}
if (isEthylBoiling()) {
System.out.println("Etheyl will boil");
}
if (isOxygenFreezing()) {
System.out.println("Oxygen will freeze");
}
if (isOxygenBoiling()) {
System.out.println("Oxygen will Boil");
}
if (isWaterFreezing()) {
System.out.println("Water will freeze");
}
if (isWaterBoiling()) {
System.out.println("Water will boil");
}
}
}
and the code for my tester is below:
import java.util.Scanner;
public class FreezingBoilingTester {
public static void main(String[] args) {
int temperature;
FreezingBoilingPoints temp1 = new FreezingBoilingPoints(0);
Scanner scan = new Scanner(System.in);
System.out.println("Please enter a temperature: ");
temperature = scan.nextInt();
System.out.println(showTempinfo());
}
}
1) don't pass the temp inside methods, because you already have this value in member variable.
2) you can change if (condition) then true else false into return (condition) and it will be the same result, just for readability .
3) you should return boolean not Boolean wrapper until you need the wrapper.
public final class FreezingBoilingPoints {
private int temperature;
public FreezingBoilingPoints(int temp) {
temperature = temp;
}
public void setTemperature(int temp) {
temperature = temp;
}
public int getTemperature() {
return temperature;
}
private boolean isEthylFreezing() {
return (temperature <= -173);
}
private boolean isEthylBoiling() {
return (temperature >= 172);
}
private boolean isOxygenFreezing() {
return (temperature <= -362);
}
private boolean isOxygenBoiling() {
return (temperature >= -306);
}
private boolean isWaterFreezing() {
return (temperature <= 32) ;
}
private boolean isWaterBoiling() {
return (temperature >= 212);
}
public String showTempinfo() {
StringBuilder result = new StringBuilder();
if (isEthylFreezing()) {
result.append("Ethyl will freeze");
result.append("\n");
}
if (isEthylBoiling()) {
result.append("Etheyl will boil");
result.append("\n");
}
if (isOxygenFreezing()) {
result.append("Oxygen will freeze");
result.append("\n");
}
if (isOxygenBoiling()) {
result.append("Oxygen will Boil");
result.append("\n");
}
if (isWaterFreezing()) {
result.append("Water will freeze");
result.append("\n");
}
if (isWaterBoiling()) {
result.append("Water will boil");
result.append("\n");
}
return result.toString();
}
}
Main:
import java.util.Scanner;
public class FreezingBoilingTester
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Please enter a temperature: ");
int temperature = scan.nextInt();
FreezingBoilingPoints temp1 = new FreezingBoilingPoints(temperature );
System.out.println(temp1.showTempinfo());
}
}
updated:
you can use String concatenation:
String result = "";
if ( condition ) {
result += "new result";
result += "\n";
}
but this is not recommended in term of performance, because each += operation will create another String object in memory holding the new result.
The problem is that your private methods are taking in a temperature and yet, you are not passing one in for your showTempinfo() method. Try removing the input parameters and using the temp set in the class. Also, you need to somehow set the temp before you call showTempinfo().
Hope this helps.
You're not passing the input that the user is giving you into the constructor for your FreezingBoilingPoints class. You're initializing that class with 0 and then asking for a temperature from the user. There's no relationship between the temperature the user provided and the class that you're using to test it.
You need to construct your FreezingBoilingPoints object in your main method, then call showTempinfo() on it. Also, your private calc methods should use the member variable; there's no need to take it as a parameter.
You need to pass the user input, temperature, into your FreezingBoilingPoints constructor. Also, the method showTempInfo() is instance specific. For example, you need to instantiate your object, temp1, by passing the user input with the constructor and then invoke temp1.showTempInfo()
Here we go:
1) All your "is..." methods are expecting for an int parameter, however when you're calling them, you're not passing anything. Remove the int parameter from either the method implementation or the method calls
2) You're missing a closing bracket for the method isWaterBoiling;
3) You marked the method "showTempinfo" as returning String, but you are not returning anything for that method. Either add the return command or remove the "String" from the method signature.
In your showTempinfo(), you try to do isEthylFreezing().
But it can't work ... isEthylFreezing is waiting for an int ... but it gets nothing ...

Categories

Resources