标题:怎么回事,明明已经返回了,说没有返回..
取消只看楼主
jxry8888
Rank: 1
等 级:新手上路
帖 子:97
专家分:0
注 册:2006-8-13
 问题点数:0 回复次数:3 
怎么回事,明明已经返回了,说没有返回..

import java.util.Random;
class Shape{
void draw(){}
void erase(){}
}

class Circle extends Shape{
void draw(){
System.out.println("Circle.draw()");
}
void erase(){
System.out.println("Circle.erase");
}
}

class Square extends Shape{
void draw(){
System.out.println("Square.draw()");
}
void erase(){
System.out.println("Square.erase");
}
}

class Triangle extends Shape{
void draw(){
System.out.println("Triangle.draw()");
}
void erase(){
System.out.println("Triangle.erase");
}
}

class RandomShapeGenerator{
private Random random = new Random();
public Shape next(){ //error, 此方法必须返回 Shape 类型的结果
switch(random.nextInt(3)){
//default:
case 0:return new Circle();
case 1:return new Square();
case 2:return new Triangle();
}
}
}
public class Duotai{
private static RandomShapeGenerator gen = new RandomShapeGenerator();
public static void main(String[] args){
Shape[] s = new Shape[4];
for( int i = 0; i< s.length; i++ ){
s[i] = gen.next();
for( int j = 0; j< s.length; j++ ){
s[j].draw();
}
}
}
}

搜索更多相关主题的帖子: void import 
2007-02-08 16:20
jxry8888
Rank: 1
等 级:新手上路
帖 子:97
专家分:0
注 册:2006-8-13
得分:0 
[QUOTE] [/QUOTE]
不知道是怎么回事?

2007-02-08 16:22
jxry8888
Rank: 1
等 级:新手上路
帖 子:97
专家分:0
注 册:2006-8-13
得分:0 
根据楼上几位的指点,我调试发现都是正确的,可是仍有一件事情不态明白.
解决方案1:加一个defaule分支.
class RandomShapeGenerator{
private Random random = new Random();
public Shape next(){
switch(random.nextInt(3)){
case 0:return new Circle();
case 1:return new Square();
case 2:return new Triangle();
default:return new Shape();//添加了一个分支.
}
}
}
解决方案2: 在switch之外加个Shape s = null;
class RandomShapeGenerator{
private Random random = new Random();
public Shape next(){
Shape s = null;
switch(random.nextInt(3)){
case 0:return s = new Circle();
case 1:return s = new Square();
case 2:return s = new Triangle();
}
return s;
}
}
对于2我能够理解,返回的s能送给public Shape next()函数返回..
但是1返回的应该只能停留在switch()中,怎么好好的却送到了外层public Shape next()函数中了......

2007-02-08 19:14
jxry8888
Rank: 1
等 级:新手上路
帖 子:97
专家分:0
注 册:2006-8-13
得分:0 
谢谢楼上的....

2007-02-09 18:16



参与讨论请移步原网站贴子:https://bbs.bccn.net/thread-120239-1-1.html




关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.059895 second(s), 8 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved