书中给出的片段如下:
static int test(int testval) {
  int result = 0;
  if(testval > target)
    result = -1;
  else if(testval < target)
    result = +1;
  else 
    result = 0; //match
    
  return result;
 
}
自己想完成这个小程序,并测试一下,添加如下(有误):
class T2 {
static int test(int testval) {
  int result = 0;
   
  if(testval > target)
    result = -1;
  else if(testval < target)
    result = +1;
  else 
    result = 0; //match
    
  return result;
 
}
}
public class T2T {
  int target = 12;
  public static void main(String[] args) {
   
    T2.test(15);
    // T2 t2 = new T2(); t2.test(13);这句是可以代替上一句的,可以忽略。    System.out.println(result);
  }
}经过几次试探性的修改,已经可以运行,想知道像上面这样写范了什么错误。我用的还是jdk6.0,例如,变量要放改在类T2中,而不可以放在主类T2T中,输入打印语句也要放到T2中,为什么放在下面的类中不行呢.

解决方案 »

  1.   

    System.out.println(result);
    result是哪儿冒出来的?
      

  2.   

    1、静态方法test中你要用T2T类中定义的target,这个target必须也是静态的,而且要这样用T2T.target
    2、result是你在方法内部定义的变量,不能在这个方法以外的地方使用
      

  3.   

    public class T2T {
      static int target = 12;
      public static void main(String[] args) {
        
      int result = T2.test(15);
      // T2 t2 = new T2(); t2.test(13);这句是可以代替上一句的,可以忽略。  System.out.println(result);//result 未定义
      }
    }
      

  4.   

    楼主的这个T2T类是一个测试类,用到的是T2中的属性和方法,当然要把变量放在T2中,而且输出的是result它是T2中的,T2T中就没有这个变量,输不出来,当然不行啊,所以你不能把它放在T2T中
    在test方法中只需要传递一个实参,所以在主类T2T中就T2.test(15)就行了,别的放在T2中
      

  5.   

    public class T2T {
      static int target = 12;  public static void main(String[] args) {
        
      int result = T2.test(target);  // T2 t2 = new T2(); t2.test(13);这句是可以代替上一句的,可以忽略。  System.out.println(result);//result 未定义
      }
    }
      

  6.   

    不可以,方法内部定义的变量的作用域就是方法内,不可能跑到方法外而且java不是C/C++,不允许方法内部定义静态变量
      

  7.   

    class T2 {
    static int test(int testval) {
      int result = 0,target=12;
        
      if(testval > target)
      result = -1;
      else if(testval < target)
      result = +1;
      else  
      result = 0; //match
        
      return result;
     
    }
    }
    public class T2T {
     //static int target = 12;
      public static void main(String[] args) {
        
      System.out.println(T2.test(15));
      // T2 t2 = new T2(); t2.test(13);这句是可以代替上一句的,可以忽略。 // System.out.println(target);
      }
    }