missing return value in a boolean method - java

Hello I am working on a project for school and im having a great deal of difficulty trying to figure why my program keeps telling me im missing a return statement in all of my methods,
Here is my code:
public class Temperature {
private int temperature;
//constructors
public int Test( int temperature )
{
temperature = temperature;
return temperature;
}
public int TempClass()
{
temperature = 0;
return 0;
}
// get and set methods
public int getTemp()
{
return temperature;
}
public void setTemp(int temp)
{
temperature = temp;
}
//methods to determine if the substances
// will freeze or boil
public static boolean isEthylFreezing(int temp)
{
int EthylF = -173;
if (EthylF <= temp)
{System.out.print("Ethyl will freeze at that temperature");}
else
return false;
}
public boolean isEthylBoiling(int temp)
{
int EthylB = 172;
if (EthylB >= temp)
System.out.print("Ethyl will boil at that temperature");
else
return false;
}
public boolean isOxygenFreezing(int temp)
{
int OxyF = -362;
if (OxyF <= temp)
System.out.print("Oxygen will freeze at that temperature");
else
return false;
}
public boolean isOxygenBoiling(int temp)
{
int OxyB = -306;
if (OxyB >= temp)
System.out.print("Oxygen will boil at that temperature");
else
return false;
}
public boolean isWaterFreezing(int temp)
{
int H2OF = 32;
if (H2OF <= temp)
System.out.print("Water will freeze at that temperature");
else
return false;
}
public boolean isWaterBoiling(int temp)
{
int H2OB = 212;
if (H2OB >= temp)
System.out.print("Water will boil at that temperature");
else
return false;
}
}

Here is the problem line:
if (EthylF <= temp)
{System.out.print("Ethyl will freeze at that temperature");}
else
return false;
The compiler thinks that return false belongs with the else branch, so if the EthylF <= temp branch is taken, the method ends without returning a value. Same goes for the rest of your boolean getters.
Properly indenting and using curly braces would help you avoid problems like that: when you see the same code formatted as follows
if (EthylF <= temp) {
System.out.print("Ethyl will freeze at that temperature");
} else {
return false;
}
you see exactly where the problem is.
Adding return true in the if branch would solve this problem.

Look at the if-else statements in your isXXXFreezing(int temp) and isXXXBoiling(int temp) methods: The section below the if-statement does not contain a return statement, only the section below the else does.
The correct code for isEthylFreezing(int temp) would be
public static boolean isEthylFreezing(int temp) {
int EthylF = -173;
if (EthylF <= temp)
{
System.out.print("Ethyl will freeze at that temperature");
return true;
}
else
return false;
}
Also in the constructor of Test you are assigning the variable temperature to itself. I guess you want to assign the function parameter temperature to a member variable of Test which is also named temperature? If so, write this.temperature = temperature;.
this refers to the current Test object and will make sure that you access the member variable.

int EthylF = -173;
if (EthylF <= temp)
{System.out.print("Ethyl will freeze at that temperature");}
else
return false;
This method only returns (false) if EthylF > temp. Otherwise, you have a print, but no return statement.
Every possible path of execution inside a non-void method must end with a return statement, or with a throw statement.

Related

Missing return statement in for-loop

I'm trying to find out if a number is a prime number or not. I created this method, which I will be using in another class later.
When compiling it tells me that I need a return statement outside the for-loop, but if I try to return the boolean value it gives me an error (cannot find symbol). What shall I return?
public class NumeroPrimo {
public static boolean primo(int numero){
for (int i=2; i<numero/2; i++){
if(numero%i==0){
return false;
}
else return true;
}
}
}
If the loop was not done (numero 1), no return would happen.
Also you return true too often.
public static boolean primo(int numero) {
for (int i = 2; i <= numero/2; i++) {
if (numero % i == 0){
return false;
}
}
return true;
}
Also for 4 <= is required.

Design a class that tells whether a number is prime or not

My homework is to Design a class named MyInteger with the following conditions:
An int data field named value that stores the int value of an integer.
A constructor that creates a MyInteger object for the specified int value.
A get method that returns the int value.
A method, isPrime() that returns true if the value is a prime number. See -section 4.10 of the text for Java code that detects prime numbers (this may vary depending on the edition you have).\
A static, isPrime(MyInteger) that returns true if the value is a prime number. Note that this method takes an object reference variable (rather than the value) as a parameter.
My problems come up in the static boolean isPrime method, stating that "/" and "%" are undefined for arguement type and in the main method in my if statement: isPrime() == true. It says to change it to static, but i already have a static boolean isPrime method and I'm supposed to have two isPrime methods according to my conditions. Thank you if you are able to help.
public class MyInteger {
public MyInteger(int value){
}
public static int getValue(){
int value = 997;
return value;
}
public boolean isPrime(){
int value = 997;
for (int i=2; i<=value/2; i++){
if(value % i == 0) {
return false;
}
}
return true;
}
public static boolean isPrime(MyInteger value){
for(int i=2; i<=value/2; i++){
if(value%i == 0){
return false;
}
}
return true;
}
public static void main(String[] args) {
MyInteger value = new MyInteger(MyInteger.getValue());
if (isPrime()==true && isPrime(value)==true){
System.out.println("Testiwng Instance method, is Prime");
System.out.println("isPrime: " + value + " is prime");
System.out.println("--------------------------------");
System.out.println("Testing Class method (That takes a reference variable) is Prime");
System.out.println("isPrime: " + value + " is prime");
}
else{
System.out.println("Testiwng Instance method, is Prime");
System.out.println("isPrime: " + value + " is not prime");
System.out.println("--------------------------------");
System.out.println("Testing Class method (That takes a reference variable) is Prime");
System.out.println("isPrime: " + value + " is not prime");
}
}
}
You don't have to go till the half of the number to check whether it is prime. You can have a loop that checks only the numbers from 2 to the square root of your number. See this - StackOverflow question about checking prime numbers
I believe you need something like this:
public class Main {
public static void main(String[] args) throws IOException {
Scanner inp = new Scanner(System.in);
int someValue = inp.nextInt();
MyInteger myInt = new MyInteger(someValue);
System.out.println("Testing instance method:");
System.out.println(myInt.isPrime());
System.out.println("Testing static method:");
System.out.println(MyInteger.isPrime(myInt));
}
}
class MyInteger {
private int value;
public MyInteger(int value) {
this.value = value;
}
public int getValue() {
return value;
}
public boolean isPrime() {
int sqrt = (int) Math.sqrt((double)value);
for(int i = 2; i <= sqrt; i++) {
if (value % i == 0) return false;
}
return true;
}
public static boolean isPrime(MyInteger myInt) {
return myInt.isPrime();
}
}
Here's a good reference for testing prime numbers What would be the fastest method to test for primality in Java?
Primarily, change your isPrime() to
boolean isPrime(long n) {
if(n < 2) return false;
if(n == 2 || n == 3) return true;
if(n%2 == 0 || n%3 == 0) return false;
long sqrtN = (long)Math.sqrt(n)+1;
for(long i = 6L; i <= sqrtN; i += 6) {
if(n%(i-1) == 0 || n%(i+1) == 0) return false;
}
return true;
}
Your value variable in the method you mentioned is of the type MyInteger, but you're trying to use it as an int. you probably want to use value.getValue() instead.
You should consider using class level variable to make use of constructor to initialize it.
Also in main() method you are trying to access non-static method (isPrime()), use it as value.isPrime().
In case you don't want to use class variable, make use of static getValue() method inside your static boolean isPrime(MyInteger value) method which solves your problem
Another way to check the prime number
public String isPrime(int number) {
if (number < 0) {
return "not a valid number";
}
if (number == 0 || number == 1) {
return "not a prime number";
}
if (number == 2 || number == 3) {
return "prime number";
}
if ((number * number - 1) % 24 == 0) {
return "prime number";
} else {
return "not a prime number";
}
}

Constant variable value on a recursive function

static boolean isPrime(int num){
int consNum = num; //something like having a non-changing value
if(consNum < 2){
return false;
}
else if( consNum % Math.round(num--/2) == 0 && num > 2)
return false;
}
else{
if(num==1)
return true;
else
return isPrime(num);
}
}
I'm trying to create a function that will determine if num is a prime number. Problem, i want a value(consNum) to stay with that value during the first call, Is there a way to do this recursively?
Edit
from:
if( (consNum % (int)(num--/2) + 0.5 == 0 )
to:
if( (consNum % Math.round(num--/2) == 0 && num > 2)
Local variables are local to the invocation of the particular method;
recursive methods are no exception.
If you wish to pass that value down the invocation chain, you need to make a second parameter for it, and pass it down explicitly:
// Users of your code invoke this method
public static boolean isPrime(int num) {
return isPrime(num, num);
}
// This overload with two parameters is the actual recursive method
private static boolean isPrime(int num, int original) {
if(original%(int)((num--/2)+0.5)==0)
return false;
}
else{
if(num==1)
return true;
else
return isPrime(num, original);
}
}
Try this
static boolean isFirst=true;
static int consNum;
static boolean isPrime(int num){
if(isFirst){ // This condition will help you to keep consNum with the initial value
consNum=num;
isFirst=false;
}
if(consNum%(int)((num--/2)+0.5)==0)
return false;
}
else{
if(num==1)
return true;
else
return isPrime(num);
}
}

Square number in java

I have to do the method, that I give a number in, if it is a Square number, it will get me true back
if it's not it will get me false back,
I wrote the code:
public class Aufgabe {
static boolean x;
public static boolean istQuadratzahl(int zahl){
int n = (int) Math.sqrt(zahl);
if (zahl%n == 0){
x = true;
}
else {
return x=false;
}
return x;
}
public static void main(String []args){
System.out.println(istQuadratzahl(6));
}
}
but when I give 6 or 8 in, it gives me true back, where did I go wonge here?
In your case, sqrt(6) is 2.44948974278. When you cast it to int it becomes 2. Of course, 6 % 2 = 0.
Try to check the result with:
if (zahl == n * n){
x = true;
}
This will do the trick:
public boolean isSquare(double zahl){
double m=Math.sqrt(zahl);
double n=(int)Math.sqrt(zahl);
if(m==n)
return true;
else
return false;
}
int sqrt = (int) Math.sqrt(inputNumber);
if(sqrt*sqrt == number) {
System.out.println(number+" is a perfect square number!");
return true;
}else {
System.out.println(number+" is NOT a perfect square number!");
return false;
}
Don't use a static variable. In fact, don't use a variable at all.
In addition, your logic is wrong. (int)Math.sqrt(12) == 3, 12%3 == 0, but 12 is not a square.
public static boolean istQuadratzahl(int zahl)
{
int n = (int) Math.sqrt(zahl);
if (n*n == zahl)
return true;
else
return false;
}
change the 'if' to this
if (zahl == n * n){

Palindrome tester

So I have the majority of the code written and it works. Except for the iterative method keeps showing that it is not a palindrome regardless of what is typed in. I am at a loss as to how to remedy it here is the code.
//David Crouse Assignment 2
import java.util.Scanner;
public class Assignment2 {
public static boolean loop = false;
//main
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Welcome to the Palindrome Checker!");
do{
System.out.print("Enter a string to check if it is a palindrome. ");
System.out.print("Enter x to exit.");
String word = input.nextLine();
word = word.replaceAll("\\s","");
word = word.toLowerCase();
//Exit Program
if(word.equalsIgnoreCase("x")){
System.out.println("End of program. Good Bye!");
System.exit(0);
}
if(iterativePalindromeChecker(word)){
System.out.println("Iterative Result: Palindrome!");
}else{
System.out.println("Iterative Result: Not a palindrome");
}
if(recursivePalindromeChecker(word)){
System.out.println("Recursive Result: Palindrome!\n");
}else{
System.out.println("Recursive Result: Not a palindrome\n");
}
loop = true;
}while (loop == true);
}
//Iterative Method
public static boolean iterativePalindromeChecker(String str){
boolean result = false;
int length = str.length();
int i, begin, end, middle;
begin = 0;
end = length - 1;
middle = (begin + end)/2;
for (i = begin; i <= middle; i++) {
if (str.charAt(begin) == str.charAt(end)) {
begin++;
end--;
}
else {
break;
}
}
if (i == middle + 1) {
result = false;
}
return result;
}
//Recusive Methods
public static boolean recursivePalindromeChecker(String str){
if(str.length() == 0 || str.length() == 1)
return true;
if(str.charAt(0) == str.charAt(str.length()-1))
return recursivePalindromeChecker(str.substring(1,str.length()-1));
return false;
}
}
Your iterative method never sets result to be true. Here's a modified version:
public static boolean iterativePalindromeChecker(String str){
int length = str.length();
int i, begin, end, middle;
begin = 0;
end = length - 1;
middle = (begin + end)/2;
for (i = begin; i <= middle; i++) {
if (str.charAt(begin) == str.charAt(end)) {
begin++;
end--;
}
else {
return false;
}
}
return true;
}
Your iterative method does not set result = true anywhere, so it really can't help it. Although I think the iterative method could be better overall. Take a close look at what is happening in the recursive one and see if you can implement some of it (like the guard conditions) more closely in the iterative method, and keep in mind that you are not limited to a single index value in a for loop either. e.g.:
public static boolean iterativePalindromeChecker(String str) {
for(int start = 0, end = str.length() - 1; start < end; start++, end--) {
if(str.charAt(start) != str.charAt(end)) {
return false;
}
}
return true;
}
I'm guessing someone once told you that a function should only have one return point, and trying to follow that led you to using a mutable result variable which screwed you here. Using break poses the same ostensible problem anyway. Save yourself the headache and just return as soon as you know the answer.
public static boolean iterativePalindromeChecker(String str) {
int begin = 0;
int end = str.length() - 1;
while (begin < end) {
if (str.charAt(begin) != str.charAt(end)) {
return false;
}
begin++;
end--;
}
return true;
}

Categories