在int上执行方法

时间:2013-04-03 23:25:15

标签: java methods compiler-errors int

我试图通过方法为int生成一个随机数。我知道这是不可能的,因为int是一个原始类型,我得到一个int不能是deferenced错误。是否还有它仍然可以使用该方法来获取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();

}

3 个答案:

答案 0 :(得分: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();

}

答案 1 :(得分:0)

int是原始类型,Integer是final,所以不,你永远不能写5.move()。 你可以编写一个只包装整数的类,但不能用它做算术。

也许Iterator<Integer>是一个值得实施的界面。

答案 2 :(得分:0)

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

相关问题