2013-04-03 34 views
0

我想通过方法为int生成一个随机数。我知道这不能做,因为一个int是一个原始类型,我得到一个int不能被引用错误。是否有其他方法可以继续使用该方法来获取int的值?在int上执行方法


public int move() 
{ 
    Random random = new Random(); 
    int generatedNum = random.nextInt(7 - 1) + 1; 

    return generatedNum; 
} 

public static void main(String[] args) 
{ 
    int player1 = 0; 
    int player2 = 0; 

    player1 = player1.move(); 
    player2 = player2.move(); 

} 
+0

对不起,请不要回答你的问题。 – David 2013-04-03 23:28:07

回答

0

你到底想干什么? 这会工作,但不知道是否是你想要的...

// made this static so you don't need a class reference 
public static int move() 
{ 
    Random random = new Random(); 
    int generatedNum = random.nextInt(7 - 1) + 1; 

    return generatedNum; 
} 

public static void main(String[] args) 
{ 
    int player1 = 0; 
    int player2 = 0; 

    // Now we just call the static method move to set the ints. 
    player1 = move(); 
    player2 = move(); 

} 
0

int是一种原始类型,Integer是决赛,所以没有,你将永远无法写5.move()。 你可以编写一个只包装一个整数的类,但是不能对它进行算术运算。

也许Iterator<Integer>是一个值得实施的接口。

0

您可以创建类似于Integer类的自己的类(不幸的是final或者您可以将其继承)。然后添加你想要的课程的任何方法。当您想要检索该值时,使用起来有点不方便,但不会太杂乱。

+0

这是幸​​运的,因此强制不变。 – Mordechai 2013-04-03 23:40:24

+0

@MouseEvent - 取决于你如何看待它。还有其他方法可以破解这个坚果。 – 2013-04-04 00:12:30

相关问题