首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >switch语句

switch语句
EN

Stack Overflow用户
提问于 2012-10-22 20:50:42
回答 8查看 192关注 0票数 0

问题是要用不同的时间来写第5段。每个段落都有不同的笼子编号和相应的动物。所以笼子1有一头狮子,笼子2有一只老虎。问题是,我不知道如何在同一段落中将两个不同的对应动物的笼号组合在一起。

我不知道如何在段落的第二行输入switch语句。我试着写println("This cage holds a“+ i);但是Eclipse给了我一个错误。如何将变量n和i同时合并到同一段落中?

代码语言:javascript
复制
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");
              }                   
        } 

    }
}
EN

回答 8

Stack Overflow用户

回答已采纳

发布于 2012-10-22 20:56:15

我会像这样写一个小方法:

代码语言:javascript
复制
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!";
           }    

}

然后,我将替换以下代码:

代码语言:javascript
复制
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.");
             }

有了这个:

代码语言:javascript
复制
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.");
             }
票数 3
EN

Stack Overflow用户

发布于 2012-10-22 20:56:43

我会使用一个数组

代码语言:javascript
复制
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]);
        }
票数 1
EN

Stack Overflow用户

发布于 2012-10-22 20:56:13

如果你按你所问的那样打印I,你会得到这样的句子:‘这个笼子里有一个1’。我怀疑这不是你要找的东西。相反,应该创建一个变量来保存动物的名称,并在switch语句中为其赋值。在此之后,您可以执行println语句。

在我看来,这就像是一项家庭作业,所以我将留给您来弄清楚如何准确地实现它:)

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13011842

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档