I've been given the following homework... We have bunnies standing in a line, numbered 1, 2, ... n The even numbered bunnies (2, 4, ..) have the normal 2 ears. The odd numbered bunnies (1, 3, ..) have 3 ears. Recursively return the number of "ears" in the bunny line 1, 2, ... n (without loops or multiplication).
I tried first with loops:
import java.util.Scanner;
public class BunnyEars {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter number of bunnies: ");
int a = in.nextInt();
int [] bunnies = new int [a];
//for loop(non-recursive method)
for(int i=0;i<bunnies.length;i++)
{
if(i%2==0)
{
bunnies[i]=2;
}
else
{
bunnies[i]=3;
}
System.out.println("Bunny ["+i+"] : "+bunnies[i]+" ears");
}
However, after removing the loop, I'm not sure how to increment the array number as shown here:
import java.util.Scanner;
public class BunnyEars {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter number of bunnies: ");
int a = in.nextInt();
int [] bunnies = new int [a];
Ears(bunnies);
// TODO Auto-generated method stub
}
public static void Ears(int [] bunnies) {
int x =0;
bunnies[x]=bunnies[x+1];
if(x<bunnies.length)
{
if(x%2==0)
{
bunnies[x]=2;
}
else
{
bunnies[x]=3;
}
}
System.out.println("Bunny ["+x+"] : "+bunnies[x]+" ears");
}
}
I will keep getting just "bunny[0]: 2 ears". There is another bunny question on stackoverflow but the output desired is different. Been searching around but can't seem to find a similar question. Any ideas?
Aucun commentaire:
Enregistrer un commentaire