You have declared your Scanner variable in the scope of your main method. The degree method has no knowledge of any variable named keyboard that exists. If you would like to read more on variable scoping (which I believe you should), you can check out the resource here. It explains in more detail the situation you are facing.
You can do 2 things
- The first being you can make the
Scanner a class variable.
- The second is to pass it into the function
Class Variable:
You can declare it above your main method, for the class variable strategy like:
public static Scanner keyboard = new Scanner(System.in);
An example of the class method is:
public static Scanner keyboard = new Scanner(System.in);
public static void main(String[] args) {
System.out.println(degree());
}
public static int degree() {
System.out.println("degree of function?");
int n = keyboard.nextInt();
return n;
}
Pass to function:
Or, you can change your method degree to take the scanner, like:
public static int degree(Scanner keyboard) {
and call it like:
degree(keyboard)
And an example of passing it into the method is:
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println(degree(keyboard));
}
public static int degree(Scanner keyboard) {
System.out.println("degree of function?");
int n = keyboard.nextInt();
return n;
}
Extra:
It should also be noted, that since you are calling degree from a static method (main), you should make degree a static method. Do so by changing:
public int degree() {
to:
public static int degree() {
keyboardwithin the scope of yourmain()method, so it's not visible in the scope of yourdegree()method. Not only that, but you can't call an instance method (degree is non-static) from a static method without having an instance of your class handy.