Missing return statement in for-loop - java

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.

Related

Method won't run because it returns no string

I'm creating a battleship game where a ship occupies 3 cells and you have to guess which cell. Once they guess it you return "hit" and if not you return "miss". Once they hit all 3 you return "kill". I've written the code but it states I still haven't returned a string.
public class SimpleBattleShip{
int[] shipCoordinates;
int numOfHits;
String updateStatus(int guess){
for(int i=0;i<shipCoordinates.length;i++){
if(guess == shipCoordinates[i]){
numOfHits++;
if(numOfHits ==3){
return "kill";
}else{
return "hit";
}
}else{
return "miss";
}
}
}
}
Have you tried just separating the NumberofHits If statement from the for loop. The problem may be the for loop iterating the whole 'hit check' for each value of 'i' which may cause it to put up false values before tallying the full amount of hits.
I've tried throwing in an else if to maybe tighten the parameters. turn it back to else if you want (this is for hit & miss).
public class SimpleBattleShip {
int[] shipCoordinates;
int numOfHits;
String updateStatus(int guess) {
for (int i = 0; i < shipCoordinates.length; i++) {
if (guess == shipCoordinates[i]) {
numOfHits++;
}
}
if (numOfHits == 3) {
return "kill";
} else if (numOfHits < 3 && numOfHits >= 1) {
return "hit";
} else {
return "miss";
}
}
}

Loop: This method must return a result of type boolean

This is the error I get:
This method must return a result of type boolean
And this is the code:
public boolean seleccionar(Aeronave otra) {
for (int i = 0; i < this.as.length; i++) {
if (otra != null && !otra.equals(this.as[i]) && otra.amenazadaPor(this.as[i])) {
return true;
} else {
return false;
}
}
}
Add a return false before the last brace. Your function doesn't return anything if this.as.length == 0, and Java is giving a compile error because of that.
The issue is that it is possible that the for-loop will loop through all elements and eventually reach the end and no result is returned. In this case we return false to ensure this.
public boolean seleccionar (Aeronave otra) {
for (int i=0; i < this.as.length; i++) {
if (otra !=null && !otra.equals(this.as[i]) && otra.amenazadaPor(this.as[i])) {
return true;
}
}
return false;
}
Your code will exit on first loop element. But when array this.as is empty, so loop will not execute, then your function is missing a return value -therefore compiler does not allow this.
To solve this issue, simply move return false after the loop ends.
public boolean seleccionar (Aeronave otra) {
for (int i=0; i < this.as.length; i++) {
if (otra !=null && !otra.equals(this.as[i]) && otra.amenazadaPor(this.as[i])) {
return true;
}
}
return false; // if no elements are matching loop condition, return false
}}

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

this method must return a result of type boolean

i am rewriting class string in java but for some method like startwith i have the same error. this is my code:
public boolean mystartwith(MyString s){
if(s.mylength() > this.mylength()){
return false;
}else{
for(int i=0 ; i<s.mylength() ; i++){
if(lesCaracteres[i] != s.lesCaracteres[i]){
return false;
}else{
return true;
}
}
}
}
and i have this error : "this method must return a result of type boolean"
If s is empty, for loop will be skipped - and your method won't return anything at all, hence the error. I'd rather add checking for this condition first.
Have to note, though, that given algorithm is flawed:
for (int i=0; i<s.mylength() ; i++){
if (lesCaracteres[i] != s.lesCaracteres[i]){
return false;
} else {
return true;
}
}
Ok, let's say I called this function with 'abc' string given as s, but instance wraps over the string 'acdef'. Guess what, your method will return true! The problem is that your loop breaks too soon: a value is returned right after checking for the first letter.
Actually, it should be written like this:
int sLength = s.myLength();
if (sLength == 0) {
return false;
// actually, it's for you to decide:
// technically each string begins with an empty string
}
if (sLength > this.mylength()) {
return false;
}
for (int i = 0; i < sLength; i++) {
if (lesCaracteres[i] != s.lesCaracteres[i]){
return false;
}
}
return true;
The key difference: true is returned only if for loop is walked over normally (i.e., exited via i < sLength condition. That, in turn, means, that all the characters of s string match those at the beginning of the string wrapped.
if(s.mylength() > this.mylength()){
return false;
}else{
for(int i=0 ; i<s.mylength() ; i++){
if(lesCaracteres[i] != s.lesCaracteres[i]){
return false;
}else{
return true;
}
}
return ____; //place true or false based on your condition
}
Suppose if(s.mylength() > this.mylength()) is not satisfied, then your code will go to the loop.
Now suppose the for loop doesn't loop, meaning s is empty. What will be returned?
Exactly! Nothing, since the loop will be skipped.
To fix this, you should return some boolean after the loop.
Java must guarantee that a boolean will be returned whatever the input, however there are conditions in which there is no return
public boolean mystartwith(MyString s){
if(s.mylength() > this.mylength()){
return false;
}else{
for(int i=0 ; i<s.mylength() ; i++){
if(lesCaracteres[i] != s.lesCaracteres[i]){
return false;
}else{
return true;
}
}
//what if s.mylength()==0 and the loop never runs?!
//therefore the code will get to here, and the method will end without a return
}
}
Note that java isn't "clever enough" to recognise that two ifs together make all posibilities. For example
boolean method(int a){
if (a>0){
return true;
}else{
if (a<=0){
return false;
}
//program can never get here, BUT java doesn't realise that
}
Still doesn't satisfy java because it imagines a scenario where both ifs are false
How to fix this depends on your specific program, but it's worth noting that the for loop will only run once at most before returning so is superfluos
You can to redefine your code like this:
public boolean mystartwith(MyString s){
if(s.mylength() > this.mylength()){
return false;
}else{
for(int i=0 ; i<s.mylength() ; i++){
if(lesCaracteres[i] != s.lesCaracteres[i]){
return false;
}else{
return true;
}
}
return false;
}
}

missing return value in a boolean method

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.

Categories