我接到了以下作业......
我首先尝试使用循环:
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");
}
}
}
但是,在删除循环后,我不知道如何增加数组编号,如下所示:
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");
}
}
我会继续得到“兔子[0]:2只耳朵”。 stackoverflow上还有另一个兔子问题,但所需的输出是不同的。一直在寻找,但似乎无法找到类似的问题。有什么想法吗?
答案 0 :(得分:1)
我选择下面的伪代码。我不想写真正的代码,因为它是一项家庭作业,而你应该从反复试验中学习。
所以这是伪代码。你必须弄清楚如何结束递归。
int ears(int[] bunnies) {
return Ears(bunnies, 0);
}
int ears(int[] bunnies, int index) {
int ears = countEars(bunnies, index);
return ears + ears(bunnies, index + 1);
}
答案 1 :(得分:-2)
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();
printEar(a - 1);
}
public static void printEar(int i) {
if (i > 0) {
printEar(i - 1);
}
System.out.println("Bunny [" + i + "] : " + ((i % 2 == 0) ? 2 : 3) + " ears");
}
}