【问题标题】:Math.random() problems in method方法中的 Math.random() 问题
【发布时间】:2013-10-30 10:43:29
【问题描述】:

这可能不是最难实现的事情,但我仍然遇到问题: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;
                   ^

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

【问题讨论】:

标签: java methods random compiler-errors


【解决方案1】:

r 仅在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

if 的范围之外声明r

我强烈建议您缩进您的代码以清晰明了并可能预防错误。

【讨论】:

    【解决方案2】:

    更改此代码

    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;   
      }
    }
    

    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;   
      }
    }
    

    原因

    变量r的作用域在if循环内所以当试图返回r时编译器没有找到r

    【讨论】:

      【解决方案3】:

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

      public static int rValue() {
          return Random.nextInt(8) * 5;
      }
      

      【讨论】:

      • 所以如果我想要我的结果范围,我这样做:return Random.nextInt(36) * 5; ??
      • 不,它就像我说的那样工作。 nextInt(8) 为您提供从 0 到 7 的整数,乘以 5 后唯一可能的结果是 0、5、10、15、20、25、30、35
      【解决方案4】:

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

      【讨论】:

        【解决方案5】:

        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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-10-18
          • 1970-01-01
          • 2013-05-22
          • 2012-05-19
          • 1970-01-01
          • 2017-05-29
          相关资源
          最近更新 更多