How to make one display in a recursive method - java

I am building a java program that executes from console, at the code I have 2 methods. first that displays all the recursive function and the second one just displays the result.
How to display just the result or where should I add the display?
public static int fibonacciR(int n) {
if(n == 0){
System.out.println(0);
return 0;
} else if(n == 1){
return 1;
}
else{
return fibonacciR(n - 1) + fibonacciR(n - 2);
}
}

First you should delete the System.out.println statement in the recursive function. So it becomes:
public static int fibonacciR(int n) {
if(n == 0){
//You removed the statement here!
return 0;
} else if(n == 1){
return 1;
}
else{
return fibonacciR(n - 1) + fibonacciR(n - 2);
}
}
Now in your main method:
public static void main (String[] args) {
...
System.out.println(fibonacciR(someNumber)); //Here you print the result of the method
...
}
Basically what you should do is remove all the print statements in the method and put it in main.

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

Method with boolean return type not working inside main()

I had static method which is to find out prime number and it is working fine but the same method i am trying to keep inside main method it is throwing errors by stating illegal modifiers for parameter and void method does not return value
the same code is working fine outside of main method, any one plz sugggest me why it is not working in main() . Thanks ..!!
My method
public static boolean isPrimeNumber(int number) {
if (number == 2 || number == 3) {
return true;
}
if (number % 2 == 0) {
return false;
}
int sqrt = (int) Math.sqrt(number) + 1;
for (int i = 3; i < sqrt; i += 2) {
if (number % i == 0) {
return false;
}
}
return true;
}
Inside main() with lot of error message
inside main
Solution
Thanks Logan --- need to add methods outside main method
my working code is added below
public class Squar {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int num = scan.nextInt();
Squar s = new Squar();
//System.out.println(s.isPrime(num));
scan.close();
System.out.println("M2 "+s.isPrimeNumber(num));
}
public boolean isPrimeNumber(int number) {
if (number == 2 || number == 3) {
return true;
}
if (number % 2 == 0) {
return false;
}
int sqrt = (int) Math.sqrt(number) + 1;
for (int i = 3; i < sqrt; i += 2) {
if (number % i == 0) {
return false;
}
}
return true;
}
}
You are getting this error because Java does not support nested function.
You are implementing method inside other method, that is not possible. to nest methods use lambdas in java 8.
have a look at Can methods in java be nested and what is the effect? [closed]

Break Iteration of Java loop with control flow with a recursive method

My attempt at recursion by trying to solve the monkey/coconut/sailor problem.
Im having issues with my for loop stopping. It just iterates though and im unsure where I went wrong.
in my 3 test cases the method testCoconuts returns the values I would like, however my loop will iterate until the last number, even if the true values are sent through the loop.
im sure its my booleans, but i havent been able to figure out what im doing wrong.
public class Test {
public static boolean testCoconuts(int s, int sr, int c){
if (c % s == 1 && sr > 0) {
Test.testCoconuts(s, sr - 1, c - (c/s) - 1);
}
else if (c % s != 1) {
return false;
}
else if (sr == 0) {
System.out.println("solved");
return true; //returns true in all 3 test cases below
}
return false;
}
public static void main(String[] args) {
//int s and sr must me entered into the test program
//as the same number, ex s= 2, sr = 2
int sailors = 3;
Test.testCoconuts(2, 2, 7); //will print solved
Test.testCoconuts(3, 3, 79); //will print solved
Test.testCoconuts(4,4,1021); //will print solved
for (int testNuts = 1; testNuts < 100; testNuts++) {
if (Test.testCoconuts(sailors, sailors, testNuts)==true) {
System.out.println("solved!");
break;
}
else {
System.out.println(testNuts);
System.out.println("next iteration");
System.out.println(testNuts);
}
}
}
}
The for-loop will run until the testCoconouts method equals true.
Now if you take a look at the method, there are four possible outcomes:
if (c % s == 1 && sr > 0)
else if (c % s != 1)
else if (sr == 0)
none of the above was satisfied
However, only in the last three of them have you explicitly stated what value the method should return.
So - in the first outcome, since nothing else is said, the method will always return false as stated outside of the if-statements. I assume you want to return the result from the recursion itself, right?
Try changing the first if-statement like this and see what happens :)
if (c % s == 1 && sr > 0) {
boolean result = Test.testCoconuts(s, sr - 1, c - (c/s) - 1);
return result;
}
(Could be done in a one-liner without the variable result, but I splitted it up for clarity)
Please remember that you call your function recursively and sending a return back to the previous function call, not to the main
Here is a solution:
public class Test {
public static boolean testCoconuts(int s, int sr, int c){
boolean flag = false;
if (c % s == 1 && sr > 0){
flag = Test.testCoconuts(s, sr - 1, c - (c/s) - 1);
}
else if (c % s != 1){
return flag;
}
else if (sr == 0){
System.out.println("solved");
return true; //returns true in all 3 test cases below
}
return flag;
}
public static void main(String[] args){
//int s and sr must me entered into the test program
//as the same number, ex s= 2, sr = 2
int sailors = 3;
//Test.testCoconuts(2, 2, 7); //will print solved
//Test.testCoconuts(3, 3, 79); //will print solved
//Test.testCoconuts(4,4,1021); //will print solved
for (int testNuts = 1; testNuts < 100; testNuts++){
boolean flag = Test.testCoconuts(sailors, sailors, testNuts);
System.out.println(testNuts);
if (flag==true){
System.out.println("solved!");
break;
}
else{
System.out.println(testNuts);
System.out.println("next iteration");
System.out.println(testNuts);
}
}
}
}

Error "Missing return statement" [duplicate]

This question already has answers here:
"Missing return statement" within if / for / while
(7 answers)
Closed 7 years ago.
I am running this java code and I am getting an error "missing return statement"
Please help. I am running using cmd in windows.
public class Fibonocci {
public static void main(String[] args) {
int i, limit, c;
i = 0;
limit = 5;
System.out.println("Fibonocci series :");
for (c = 1; c <= limit; c++) {
System.out.println(fib(i));
System.out.println("/n");
i++;
}
}
public static int fib(int p) {
if (p == 0) {
return 0;
}
if (p == 1) {
return 1;
} else if (p > 1) {
return (fib(p - 1) + fib(p - 2));
}
}
}
Your code doesn't return anything if p<0.
You can change it to :
public static int fib(int p){
if (p<=0) // or perhaps you wish to throw an exception if a negative value is entered
return 0;
else if (p==1)
return 1;
else // when you end the if statement in else instead of else-if
// your method is guaranteed to return something for all inputs
return(fib(p-1)+fib(p-2));
}
You are missing a default return. You are returning from if and else if.
What if both conditions not satisfied ? You need to provide that as well.
I would like to suggest to return -1 id both conditions not satisfied which is for negative numbers negative
public static int fib(int p) {
if (p == 0)
return 0;
else if (p == 1)
return 1;
else if (p > 1)
return (fib(p - 1) + fib(p - 2));
else
return -1;
}

How to Update a Counter for Fibonacci using Recursion?

Here's the deal I want to count the recursive calls for a basic Fibonacci code. I already have it so the values will print out in column format but I don't know how to update the recCounter. I think I have to add recCounter++; Somewhere and I don't know where
public static int recursionFibonacci(int n) {
recCounter = 1;
return fibonacci1(n);
}
public static int fibonacci1(int n) {
if (n == 1 || n == 2) {
return 1;
} else {
return fibonacci1(n-1) + fibonacci1(n-2);
}
}
You should increment the counter every time you call the function:
public static int fibonacci1(int n) {
recCounter++; // <<-- here
if (n == 1 || n == 2) {
return 1;
} else {
return fibonacci1(n-1) + fibonacci1(n-2);
}
}

Categories