书上要改错的题我搬上来了
刚学Java不久(大佬别管我,我是纯小白),也算是有一点c++的基础,打课后题的时候产生的问题
题目
public class ExerciseOne {
double findExciseOne(double a, double b, double c) {
return (a + b + c) / 3.0;
}
public static void main(String[] args) {
double a = 5.1;
double b = 20.32;
double c = 32.921;
System.out.print(findExciseOne(a, b, c));
}
}
换成c++不改变原意可以直接输出,但Java就是不行
沙雕过程
先看看报的什么错,静态和非静态不匹配
然后因为eclpse可以检查并改正,就把函数前加了个static,对上了
但是不能就这么算了不是,
既然是不匹配,我就把main前的static删了,那不就匹配上了,又报错
然后就继续找别的方法
刚学的时候可以直接传进一个变量(这是错的,现在才明白过来当时变量都赋了值)
设置了一个d变量,是不是print()不能放函数,(c的输出没怎么看过以为是知识缺漏)
就把d传进去,结果(Cannot make a static reference to the non-static method findExciseOne(double, double, double) from the type ExerciseOne)double kill
之后就开始找大佬啊~~~~
解决两个问题
1.有什么方法可以不使函数静态
2.为什么main必须为静态
解释
- java中静态方法不可以直接调用非静态方法和成员,也不能使用this关键字
(编译器报错翻译就是把非静态的方法放到静态的引用中) - 原因解释:
因为main是静态的,在Java中静态的属性和方法并不存在于类中,即使类不存在该静态还静态,它在Java虚拟机安装类的时候已经被分配对象了,但是类中的非静态的属性或者方法必须有对象,也就是得实例化。(这有点乱往下看)
所以在静态方法中调用非静态方法时,编译器会报错
(Cannot make a static reference to the non-static method findExciseOne(double, double, double) from the type ExerciseOne)。 - Java中的main函数本质上也是类的方法(从Java的面向对象性质看的出来:一切皆对象),如果直接去掉主函数前的static,也会报错
( main 方法不是类 capterfour.ExerciseOne 中的static, 请将 main 方法定义为:
public static void main(String[] args)) - 原因解释:
当main不在静态时需要首先将main实例化(这个我瞎改,没改出来,欢迎尝试),对于运行一个程序的main来说不现实,所以把main直接定义为静态
最后涂涂改改就成了这个样纸
package capterfour;
public class ExerciseOne {
/*
* static double findExciseOne(double a, double b, double c) {
* return (a + b + c) / 3.0;
* }
* 这个是另一种方法也是对的,但是感觉意义不大
*/
double findExciseOne(double a, double b, double c) {
return (a + b + c) / 3.0;
}
public static void main(String[] args) {
double a = 5.1;
double b = 20.32;
double c = 32.921;
// double d = 0.0;
// d=findExciseOne(a, b, c);
// System.out.print(d);
// System.out.print(findExciseOne(a, b, c));
ExerciseOne tc = new ExerciseOne();
System.out.print(tc.findExciseOne(a, b, c));
}
}