Java (plz don\'t copy paste) Create a program that will do one of two functions
ID: 3836630 • Letter: J
Question
Java (plz don't copy paste)
Create a program that will do one of two functions using a menu, like so:
1. Do Catalan numbers
2. Do Fibonacci numbers (recursive)
0. Quit
Enter selection: 1
Enter Catalan number to calculate: 3
Catalan number at 3 is 5
1. Do Catalan numbers
2. Do Fibonacci numbers (recursive)
0. Quit
Enter selection: 2
Enter Fibonacci number to calculate: 6
Fibonacci number 5 is 8
Create a function of catalan that will take a parameter and return the Catalan number. Also create a function of Fibonacci that will take a parameter, calculate using recursion the Fibonacci number and return the number.
Main will have a do/while loop that will print the menu, enter the selection, and call the functions. Have it quit on 0.
Explanation / Answer
import java.util.*;
public class Menu{
static int catalan(int num)
{ int response = 0;
if (num <= 1)
{
return 1;
}
for (int j = 0; j< num; j++)
{
response += catalan(j) * catalan(num - j - 1);
}
return response;
}
static int fibRecursive(int num)
{
if(num == 1 || num == 2)
{ return 1; }
return fibRecursive(num-1) + fibRecursive(num -2);
}
public static void main(String []args){
int choice;
Scanner s = new Scanner(System.in);
System.out.println("Please select one of the options from menu");
do{
System.out.println("1.Do Catalan number");
System.out.println("2.Do Fibonacci Series");
System.out.println("0.Quit");
choice = s.nextInt();
switch(choice)
{
case 1:
{int num, catNum;
System.out.println("Enter catalan number to calculate");
num = s.nextInt();
catNum = catalan(num);
System.out.println("Catalan of" + num + "is" + catNum);
break;
}
case 2:
{
int num,fibNum;
System.out.println("Enter fibonacci number to calculate");
num = s.nextInt();
fibNum = fibRecursive(num);
System.out.println("Fibonacci of" + num + "is" + fibNum);
break;
}
case 0:
{
System.out.println("You choose to exit");
System.exit(0);
break;
}
}
}while(choice != 0);
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.