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)

  • برمجة جافا

Quiz 1 - CS150 - Section 371

We have number of bunnies and each bunny has two big ears, we want to compute the total ears of n bunnies, where n is a positive integer entered by the user.

 

Write a java class (BunnyEars.java) that solves such a problem by using only the recursion approach (without using loop or multiplication). 

 

In the class declaration, you will have three methods:

Your program main method as shown in the code below which reads from the user the total number of bunnies and calls the following two methods:

o The recursion method bunny(int n) as public static method to count the total number of ears.

o print(int count) method as public non-static method to print the total number of ears (count) of n bunnies. 

الأجوبة

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);
	
	}
}
هل كان المحتوى مفيد؟

تبحث عن مدرس اونلاين؟

محتاج مساعدة باختيار المدرس الافضل؟ تواصل مع فريقنا الان لمساعدتك بتأمين افضل مدرس
ماهو التخصص الذي تبحث عنه؟
اكتب هنا...