Java sign of number code - java

I am trying to return the sign of a number using my code here but there seems to be a problem with my use of return? Help por favor?
import java.util.*;
public class ReturnTest {
public static int sign(int n) {
if (n > 0)
return 1;
else if (n == 0)
return 0;
else if (n < 0)
return -1;
}

public static int sign(int n)
{
if (n > 0)
return 1;
else if (n < 0)
return -1;
return 0;
}
The last if-else was unnecessary. I've re-ordered to the 'usual' way of falling through at zero. Writing the code like this is shorter, cleaner and easier to understand

The problem is that you're not returning a method from all the paths in your method. You can see this by indenting the code accordingly based on Oracle Java Code Conventions:
public static int sign(int n) {
if (n > 0) {
return 1;
} else if (n == 0) {
return 0;
} else if (n < 0) {
return -1;
}
}
//needs a return here...
}
This can be fixed by having a default return value at the bottom. The code may look like:
public static int sign(int n) {
if (n > 0) {
return 1;
} else if (n == 0) {
return 0;
}
return -1;
}
There are other ways to implement this, but I prefer to do a fix based on your current implementation.
From your comments, looks like you're in your first steps to learn Java. To make an application, you need an entry point. This is marked by the main method which has this signature:
public static void main(String[] args)
So, in your current class, you can add this method and use it to call your sign method. I'll show a very basic sample:
public class ReturnTest {
public static int sign(int n) {
if (n > 0) {
return 1;
} else if (n == 0) {
return 0;
}
return -1;
}
public static void main(String[] args) {
int n = 10;
int signOfN = sign(n);
System.out.println("The sign of " + n + " is: " + signOfN);
}
}
It depends to you to adapt this code for your needs. I highly recommend you learn the basics. You can start here:
Trail: Learning the Java Language, Oracle tutorial about Java basic concepts.
Lesson: A Closer Look at the "Hello World!" Application, just to have a better understanding about the most basic application, the "Hello World!".

Spare the last if (if (n < 0)) because otherwise there is a theoretical branch where the function is never left!
Each branch must return!

Related

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]

How to make one display in a recursive method

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.

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

Java recursion; how can I simplify what I have?

I have to write the following recursion method:
public static int countA(String s)
Yet I find it impossible to do this without declaring a counter and position variable; like so:
public static int countA(String s, int position) {
int count = 0;
if( s.charAt(position) == 'A' )
count++;
if( position + 1 < s.length() ) {
count += countA(s, position + 1);
}
return count;
}
How can I simplify my answer so that my method is the same as the one listed?
EDIT: Yes, I want to count all A's inside a string.
Try this:
public static int countA(String s) {
int count = 0;
if (s == null)
return 0;
if (s.length() == 0)
return 0;
if (s.charAt(0) == 'A')
count++;
return count + countA(s.substring(1));
}
There are two forms of recursion,
Tail Recursion : The return value is calculated as a combination of the value of current subroutine and the return value of the next call. Example,
int factorial(int a) {
if(a==0)
return 1;
else
return a * factorial( a-1 );
}
Accumulator based recursion : You accumulate the results by adding an additional parameter and return the accumulated value.
int factorial(int a, int fact) {
if(a==0)
return fact;
else
return factorial(a-1, a*fact);
}
Obviously what you have here is accumulator based, while you can improve it to Tail recursion.
Tail recursion is considered more readable, while it can cause a StackOverflow! (no pun intended). This is because it has to push the current value to a stack, before calling subroutine again. And when you make a large number of such calls, this stack might go over its limit.
Some compilers optimize tail recursion to accumulator based in order to avoid this problem.
What about:
public static int countA(String s) {
if(s==null) return 0;
if(s.length()==0) return 0;
if( s.charAt(0) == 'A' )
{
return 1 + countA(s.substring(1));
} else
{
return countA(s.substring(1));
}
}
I think something like this should do the trick
Here we are assuming that countA returns the number of As inside String s
public static int countA(String s)
{
if(s.length()==0) return 0; // return 0 if string is empty
else
{
// if the first char is A add 1 to the answer, recurse
if(s.toCharArray()[0])=='A') return 1+countA(s.subString(1,s.length()));
// else add nothing to the answer, recurse
else return countA(s.subString(1,s.length()));
}
}
You move the position variable out of the method and make it static(since your countA() is also static).
static int position = 0;
public static int countA(String s) {
int count = 0;
if( s.charAt(position) == 'A' )
count++;
if( position + 1 < s.length() ) {
position++;
count += countA(s);
}
return count;
}
Ideally you have the termination condition first, which then usually simplifies the code by reducing indentation/nesting and have a "do nothing" action for it (typically requiring one more iteration than absolutely required).
You also don't need the local variable!
public static int countA(String s, int position) {
if (position == s.length())
return 0;
return (s.charAt(position) == 'A' ? 1 : 0) + countA(s, position + 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