user4172380
user4172380

Reputation:

I don't understand how to get my program to return an int value from an integer

 public static int getComputerMoveAI(int left)
 {
    Integer returnValue = 0;
    Integer place = nimMachine.size() - left;
    returnValue = nimMachine.get(place).get(((int)Math.random()*place)+1);
    plays[place] = returnValue;
    return intValue(returnValue);
 }

I want my program to return an int value so that main can work with that but I don't understand how to make that happen. I know it's not correct but I put where I want to change the Integer to an int. I have to use Integer for my arraylist.

Upvotes: 0

Views: 171

Answers (2)

user289086
user289086

Reputation:

Integer and int will get changed from one to the other automatically as the system needs. This is known as autoboxing.

This can be seen int he following code:

class Ideone {
    public static int foo() {
        Integer rv = Integer.valueOf(42);
        return rv;
    }

    public static Integer bar() {
        int rv = 42;
        return rv;
    }

    public static void main (String[] args) {
        System.out.println(foo());
        System.out.println(bar());
    }
}

(ideone)

This prints out 42 and 42. But note that the rv in foo() is an Integer and in bar() it is an int - the 'wrong' type for each return value.

What is going on here is that the int is getting converted to an Integer in bar() and in foo(), the Integer is getting converted to an int for you through the boxing and unboxing process.

You don't need to do an returnValue.intValue() or Integer.valueOf(someInt) or any other method call to convert one to the other in this case. Let the system do it for you. It will work.

Upvotes: 2

Mr Zorn
Mr Zorn

Reputation: 1913

The Integer class has an intValue() method on it. Check the javadocs - they are your friend: http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#intValue%28%29

Upvotes: 0

Related Questions