有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!


共 (4) 个答案

  1. # 2 楼答案

    When I try the following, function2 does not recognise the variable variable1. Should this be the case?

    对。它是一个局部变量——声明它的方法的局部变量。该方法可以在同一个线程(不同的堆栈级别)和几个不同的线程上执行多次——该方法的每次调用都有一个单独的变量

    你应该复习一下Variables section of the Java tutorial

  2. # 3 楼答案

    除非将其作为参数传递给function2,否则无法识别

    例如

      int variable1;
      function2(variable1);
    
  3. # 4 楼答案

    你要么让变量成为一个字段,要么把它传递给函数的参数

    public static void main(String[] args) {
        int variable = 0;
        function2(variable);
    }
    
    public static void function2(int argument) {
        //argument is = variable
    }
    
    /* or ... */
    
    private static int variable;
    
    public static void main(String[] args) {
       variable = 0;
       function2();
    }
    
    public static void function2() {
        //variable is usable
    }