Java is pass by reference. You cannot modify the value of a primitive type (such as an integer) by passing it into a function, because the value of that variable is passed into the function, not a pointer to it. Whatever you change in the function only happens inside the function. You can fix your problem in one of two ways:
Solution 1: Modify your function to return a value and assign the variable you need to change as the result of the function call. The function will look like this:
private static void newNumber()
{
int userInput;
// get user input, error check
return userInput;
}
And the call will look like this:
myInt = newNumber();
Notice you do not need to pass in the Scanner
or an int
as you can put that all in the newNumber
function (unless you want to reuse a Scanner
object you created earlier).
Solution 2: Encapsulate the int
in a class. This is probably unnecessary and over-complicated for this problem, but if you make a class with the int inside it, you can create an object with your int inside it, pass a pointer to that object into a function, and use that pointer as it will still point to the object you created earlier.