问题是要用不同的时间来写第5段。每个段落都有不同的笼子编号和相应的动物。所以笼子1有一头狮子,笼子2有一只老虎。问题是,我不知道如何在同一段落中将两个不同的对应动物的笼号组合在一起。
我不知道如何在段落的第二行输入switch语句。我试着写println("This cage holds a“+ i);但是Eclipse给了我一个错误。如何将变量n和i同时合并到同一段落中?
import acm.program.*;
public class ZooAnimals extends ConsoleProgram {
private static final int START = 1;
public void run(){
for (int n = START; n <=5; n++ ) {
println("This animal is in cage" + n);
println("This cage holds a " ); <---- type of animal goes in here.
println("Wild animals are very dangerous.");
}
for(int i = START; i<=5; i++) {
switch(i) {
case 1: println("lion");
case 2: println("tiger");
case 3: println("elephant");
case 4: println("snakes");
case 5: println("hippo");
}
}
}
}发布于 2012-10-22 20:56:15
我会像这样写一个小方法:
public String getAnimal(int cage)
{
switch(cage) {
case 1: return "lion";
case 2: return "tiger";
case 3: return "elephant";
case 4: return "snakes";
case 5: return "hippo";
default: return "Animal Not Found!";
}
}然后,我将替换以下代码:
for (int n = START; n <=5; n++ ) {
println("This animal is in cage" + n);
println("This cage holds a " ); <-----------type of animal goes in here.
println("Wild animals are very dangerous.");
}有了这个:
for (int n = START; n <=5; n++ ) {
println("This animal is in cage" + n);
println("This cage holds a " + getAnimal(n)); <-----------type of animal goes in here.
println("Wild animals are very dangerous.");
}发布于 2012-10-22 20:56:43
我会使用一个数组
public class ZooAnimals extends ConsoleProgram {
String[] animals = "none,lion,tiger,elephant,snake,hippo".split(",");
public void run() {
for (int n = START; n < animals.length; n++) {
println("This animal is in cage" + n);
println("This cage holds a " + animals[n]);
println("Wild animals are very dangerous.");
}
for (int i = START; i < animals.length; i++) {
println(animals[i]);
}发布于 2012-10-22 20:56:13
如果你按你所问的那样打印I,你会得到这样的句子:‘这个笼子里有一个1’。我怀疑这不是你要找的东西。相反,应该创建一个变量来保存动物的名称,并在switch语句中为其赋值。在此之后,您可以执行println语句。
在我看来,这就像是一项家庭作业,所以我将留给您来弄清楚如何准确地实现它:)
https://stackoverflow.com/questions/13011842
复制相似问题