我的问题> toString有一个错误,说我还没有添加返回值;

我做了什么,
我做了一个产生随机运气或随机时间的类

public randomLuckOrTime(){
    Random rand = new Random();
    int t = rand.nextInt(2);

    if(t == 0){
        randomTime();
    }
    else if(t == 1){
        randomLuck();
    }

}


两类

public Luck randomLuck(){

    int [] num = {1,2,3,4,5,6,7,8,9,10,5,6,6,9,17};


    Luck q = new Luck();
    Random rand = new Random();

    int Rand = rand.nextInt(15);
    q.setLuck(num[Rand]);
    this.numbr = q.getLuck();


    return q;

}

public Time randomTime(){

    int [] TImeList = {10,20,30,40,50};

    Time l = new Time();
    Random rand = new Random();

    int Rand = rand.nextInt(5);
    l.setTime(TimeList[Rand]);
    this.Time = l.getTime();

    return l;
}


我的toString,我想根据打印出来的两个选项而有所不同。

public String toString(){
    if(this.Time == 0){
        String s = " " +"\n";
        s += "Random Number: " + this.numbr+ "\n";

        return s;
    }
    else if(this.numbr = 0){
        String s = " " +"\n";
        s += "Random Time: " + this.Time+ "\n";

        return s;
    }
}

最佳答案

这是一个错误,因为两个条件都可能不是true,因此您将没有return。如果你做类似的事情,

String s = " " +"\n";
if(this.Time == 0){
    s += "Random Number: " + this.numbr+ "\n";
}
else if(this.numbr == 0){ // <-- note ==
    s += "Random Time: " + this.Time+ "\n";
}
return s;


更少的代码以及合法代码。或者,您可以消除s并执行类似的操作

if(this.Time != 0){
    return String.format("Random Time: %d%n" + this.Time);
}
else if(this.numbr != 0){
    return String.format("Random Number: %d%n", this.numbr);
}
return "";

10-07 18:55
查看更多