Create a recursive method to print out all the emotions recursively. import java
ID: 3688155 • Letter: C
Question
Create a recursive method to print out all the emotions recursively.
import java.util.Arrays;
import java.util.Scanner;
//recursion
public class Exercise5 {
public static String Define_Emotion(String sound){
String emotion="none"; //init a string variable called emotion
switch(sound){
case "laugh":
emotion = "happy";
break;
case "sneeze":
emotion = "worried";
break;
case "sigh":
emotion = "hopeful";
break;
case "yummy":
emotion = "hungry";
break;
case "cheers":
emotion = "festive";
break;
//default:System.out.println("Invalid sound");
}//switch
return emotion;
}//end of the Define_Emotion method
public static void Define_Emotion_Recursive(String[] sounds, int n){
String emotion="none";
if(n==(sounds.length-1)){
System.out.println(Define_Emotion(sounds[n]));
}else{
System.out.println(Define_Emotion(sounds[n]));
Define_Emotion_Recursive(sounds, n+1);
}
}
public static void main(String[] args){
String sound = "none";
String emotion = "none";
String[] sounds = new String[5];
int userInput = 0;
Scanner input = new Scanner(System.in);
while((!(sound.equals("whistle")))&&(userInput<5)){
System.out.print("Provide a sound = ");
sounds[userInput] = input.next();
sound = sounds[userInput];
//emotion = Define_Emotion(sound);
//System.out.println("The emotion is "+ emotion);
userInput++; //userInput = userInput + 1;
}
//Call recurive method
Define_Emotion_Recursive(sounds,0);
}//end of the main method
}
Explanation / Answer
This function will take the sounds array and its size as input, and will print all the emotions, recursively to the screen.
public static void Print_Emotions_Recursive(String[] sounds, int n)
{
if(n == 0)
return;
System.out.print(sounds[n-1] + " ");
Print_Emotions_Recursive(sounds, n-1);
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.