代码如下,为什么函数f里使用switch会出错,而if可以使用呢?如何改正,请大家指点
public class Hi
{
int a;
public Hi(int a)
{
this.a=a;
} static Hi f(int x,Hi aa,Hi bb)
{
switch(x)
{
case 1: return aa;
case 2: return bb;
case 3: return new Hi(3);
}
/*if (x==1)
return aa;
else
if(x==2)
return bb;
else
return new Hi(3);*/
} public static void main(String[] args)
{
Hi aa=new Hi(1);
Hi bb=new Hi(2);
Hi cc;
for (int i=1;i<4 ;i++ )
{
cc=f(i,aa,bb);
System.out.println("the "+i+"times:"+cc.a);
}
}
}

解决方案 »

  1.   

    此回复为自动发出,仅用于显示而已,并无任何其他特殊作用
    楼主截止到2008-06-19 12:10:05的汇总数据:
    注册日期:2008-6-19
    上次登录:2008-6-19
    发帖数:1
    结贴数:0
    结贴率: 0.00%
    如何结贴请参考这里:http://topic.csdn.net/u/20080501/09/ef7ba1b3-6466-49f6-9d92-36fe6d471dd1.html
      

  2.   

    你的switch 如果不是 1,2,3 那怎么办?没有返回值了!
      

  3.   

    switch(x)
    {
       case 1: return aa;
       case 2: return bb;
       default : return new Hi(3);
    }
      

  4.   

    缺个自定义错误输出
    default : return new Hi(数字);
      

  5.   

            switch (x)
            {
                case 1:
                    return aa;
                case 2:
                    return bb;
                case 3:
                    return new Hi(3);
                default:
                    return new Hi(3);
            }
      

  6.   

    public class Hi
    {
        int a;
        public Hi(int a)
        {
            this.a=a;
        }    static Hi f(int x,Hi aa,Hi bb)
        { Hi yy=null;
            switch(x)
            {
                case 1: yy=aa;
                break;
            
                case 2: yy=bb;
              break;
                case 3: yy=new Hi(3);
               break;
            }
            return yy;
          /*  if (x==1)
                return aa;
            else
                if(x==2)
                    return bb;
                else
                    return new Hi(3);*/
        }    public static void main(String[] args)
        {
            Hi aa=new Hi(1);
            Hi bb=new Hi(2);
            Hi cc;
            for (int i=1;i<4 ;i++ )
            {
                cc=f(i,aa,bb);
                System.out.println("the "+i+"times:"+cc.a);
            }
        }
    }