书中给出的片段如下:
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中,为什么放在下面的类中不行呢.
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中,为什么放在下面的类中不行呢.
result是哪儿冒出来的?
2、result是你在方法内部定义的变量,不能在这个方法以外的地方使用
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 未定义
}
}
在test方法中只需要传递一个实参,所以在主类T2T中就T2.test(15)就行了,别的放在T2中
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 未定义
}
}
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);
}
}