Java: “error: cannot find symbol”

大兔子大兔子 提交于 2019-12-30 19:48:47

问题


(Rookie mistake, I'm sure.)

I'm a first year computer science student, and attempting to write a program for an assignment, with the code;

import java.util.Scanner;
public class Lab10Ex1 {

   public static void main(String[] arg) {

    Scanner keyboard = new Scanner(System.in);
    System.out.println("Please type a number: ");
    int n = keyboard.nextInt(); 
    calcNumFactors();
  }
  public static void calcNumFactors(){

   System.out.print(n + 1);

  }

}

But upon compiling, I get the error;

Lab10Ex1.java:10: error: cannot find symbol System.out.print(n + 1); ^

symbol: variable n

location: class Lab10Ex1

If someone could explain to me what I've done wrong, or how to fix it, I would greatly appreciate it.


回答1:


The n variable was declared in the main method and thus is visible only in the main method, nowhere else, and certainly not inside of the calcNumFactors method. To solve this, give your calcNumFactors method an int parameter which would allow calling methods to pass an int, such as n into the method.

public static void calcNumFactors(int number) {
   // work with number in here
}

and call it like so:

int n = keyboard.nextInt(); 
calcNumFactors(n);



回答2:


You must declare the variable n in public static void calcNumFactors()

In your code, you have to pass the value of n as an argument to the function calcNumFactors() as Hovercraft Full Of Eels said.




回答3:


import java.util.Scanner;
public class Lab10Ex1 {

   private static int n;

   public static void main(String[] arg) {
    Scanner keyboard = new Scanner(System.in);
    System.out.println("Please type a number: ");
     n = keyboard.nextInt(); 
    calcNumFactors();
  }
  public static void calcNumFactors(){

   System.out.print(n + 1);

  }
}


来源:https://stackoverflow.com/questions/20137581/java-error-cannot-find-symbol

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!