We aren't doing much recursion in my java course, but I wanted to learn about it so I wrote a little test program. The problem with the program is that after the getLength
or getWidth
methods are recalled by recursion, it does not use the user's input in the return statements, resulting in the displayArea
method returning area as 0.0. If you could point out my mistake and/or a solution, that would be helpful. Below is the code:
package recursiontest;
import java.util.Scanner;
public class RecursionTest
{
static void main(String[] args) {
// TODO code application logic here
double length = getLength();
double width = getWidth();
double area = getDimensions(length, width);
displayArea(area);
}
public static double getLength(){
double length = 0;
Scanner in = new Scanner(System.in);
System.out.print("Please enter the rectangle's length: ");
if(in.hasNextDouble()){
length = in.nextDouble();
}
else{
System.out.println("Input must be a double.");
getLength();
}
return length;
}
public static double getWidth(){
double width = 0;
Scanner in = new Scanner(System.in);
System.out.print("Please enter the rectangle's width: ");
if(in.hasNextDouble()){
width = in.nextDouble();
}
else{
System.out.println("Input must be a double.");
getWidth();
}
return width;
}
public static double getDimensions(double length, double width){
double area = 0;
area = length * width;
return area;
}
public static void displayArea(double area){
System.out.println("Area = "+area);
}
}
in getLength()
, you call recursively getLength()
, but you don't use the result, which means that return length
still returns 0
replace getLength();
by
length = getLength();
(same for the width)