0

这可能不是最难实现的事情,但我仍然遇到问题:S:

在我的小程序中,我正在模拟纸牌游戏(http://tinyurl.com/pf9fhf4),我需要从 [0,35] 范围内以 5 为增量生成一个随机数。因此,可能的值应该是: 0, 5, 10, 15, 20, 25, 30, 35。我首先在单独的课程中尝试过这个,如下所示:

class RandomValue {
public static void main (String [] args){

int i =0;

    do {
    int n = (int) (Math.random()*36 );
        if (n%5 ==0){
        System.out.println(n);
        i++;
        }

    } while (i <1); 
  }
}

这有效!

当我尝试创建一个返回此生成值的方法时:

public class Tarot {

public static int rValue (){

int i =0;

    do {
    int n = (int) (Math.random()*36 );
        if (n%5 ==0){
        int r =n;
        i++;
        }       
    }while(i<1);
    return r;   
  }
}

它返回一个错误:

Tarok.java:14: error: cannot find symbol
            return r;
                   ^

我做错了什么,任何建议如何以更漂亮的方式做到这一点?

4

5 回答 5

2

r is known only in the scope of the if:

if (n%5 ==0) {
    int r =n;  //r is known only between the braces of the if
    i++;
} 
//I know r here said no one ever

Declare r outside the scope of the if.

I highly recommend you to indent your code for clarity and possible bug prevention.

于 2013-10-30T10:44:49.023 回答
1

change this code

public class Tarot {

public static int rValue (){

int i =0;

    do {
    int n = (int) (Math.random()*36 );
        if (n%5 ==0){
        int r =n;
        i++;
        }       
    }while(i<1);
    return r;   
  }
}

to

public class Tarot {

public static int rValue (){

int i =0;
int r =0
    do {
    int n = (int) (Math.random()*36 );
        if (n%5 ==0){
        r=n;
        i++;
        }       
    }while(i<1);
    return r;   
  }
}

reason

The scope of variable r is within if loop So when trying to return r compiler did not find r

于 2013-10-30T10:45:04.443 回答
1

生成可被 5 整除的数字更容易:

public static int rValue() {
    return Random.nextInt(8) * 5;
}
于 2013-10-30T10:48:33.480 回答
0

您好,您正在 while 循环范围内定义“r”变量,但试图在方法范围内返回它。因此,只需将“r”变量定义移动到方法的开头,就像对“i”所做的那样。

于 2013-10-30T10:47:25.133 回答
0

r变量未定义,return语句看不到。尝试这样做:

int r = 0;
do {
int n = (int) (Math.random()*36);
    if (n%5 == 0){
    r = n;
    i++;
    }       
} while(i < 1);
return r; 

你用这个做什么?你试图找到第一个随机数,共享 5

于 2013-10-30T11:08:18.223 回答