Write a java class (BunnyEars.java) that compute the total ears of n bunnies by using only the recursion approach (without using loop or multiplication)
- برمجة جافا
- 2021-12-03
- softwareEngineer
الأجوبة
import java.util.Scanner;
public class BunnyEars{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.print("Enter number of bunnies: ");
int n = input.nextInt();
// validate the user input where n must not be less than 0
while (n < 0){
System.out.print("Try agian! Enter number of bunnies: ");
n = input.nextInt();
}
// call bunny method
int count = bunny(n);
//call print method
BunnyEars object = new BunnyEars();
object.print(count);
}
public static int bunny(int n){
if(n==0)
return 0;
else
return bunny(n-1) + 2;
}
public void print(int count){
//print the total number of ears (count)
System.out.println("Total ears are: " + count);
}
}
أسئلة مشابهة
القوائم الدراسية التي ينتمي لها السؤال