Reputation:
This is probably a really stupid question, but I'm having problems calling methods in java. For my computer science class I am instructed to write a single program with multiple methods. In one method I am to prompt the user to enter an integer, return that integer and store it in a variable. The next method is to be passed the integer from the previous method and return true if the integer is odd and false if it is not.
My problem is this, when I try to call the second method from the main method, I get an error message saying "cannot find symbol. symbol number" I'm sure it has something to do with the scope of the variable only existing within the getInput method, but I don't know how to get the program to print the value from my second method if it won't recognize my variable from the first method.
Here's what I have come up with so far. (You can disregard the method named printBanner, that one works, I'm just having trouble with the next two, getInput and isOdd)
import java.util.Scanner;
public class MethodlabPractice {
public static void main(String[] args) {
printBanner();
getInput();
isOdd(number);
} // end main
public static void printBanner () {
for (int count = 0; count != 10; count++)
System.out.println("Beth Tanner");
} // end printBanner
public static int getInput() {
Scanner input = new Scanner(System.in);
System.out.println("Please enter an integer:");
int number = input.nextInt();
System.out.println(number);
return number;
} // end getInput
public static boolean isOdd(int number) {
boolean odd = number % 2 != 0;
return odd;
} // end isOdd
}// end class
Upvotes: 5
Views: 257
Reputation: 159754
You haven't defined the variable number
within the scope of the main
method.
int number = getInput();
isOdd(number);
Upvotes: 7
Reputation: 5637
getInput returns int, save it and then pass it
int number = getInput();
isOdd(number);
instead what you are trying to do is
getInput();
isOdd(number); // passing number, but number is not defined
Or you can do:
isOdd(getInput());
Upvotes: 4
Reputation: 29
You're passing the argument number
to isOdd()
method inside your main
method. But number
must be declared before it can be passed.
Upvotes: 1