我正在尝试获取两个浮点值,查看哪一个更大,并返回true或false。这是我的代码:
import java.util.Scanner;
public class Four_Ten
{
public static void main(String []args){
double num1, num2 = 0;
Scanner scan = new Scanner(System.in);
System.out.println("Enter a floating point value:");
num1 = scan.nextFloat();
System.out.println("Enter another floating point value:");
num2 = scan.nextFloat();
System.out.println(calcGreater(num1, num2));
}
public double calcGreater(double a, double b){
boolean greater = false;
if (a > b){
greater = true;
}
if (b > a){
greater = false;
}
return greater;
}
}
我收到以下错误:
non-static method calcGreater(double, double) cannot be referenced from a static context
我该如何解决这个问题?
答案 0 :(得分:2)
public class Four_Ten
{
public static void main(String []args){
double num1, num2 = 0;
Scanner scan = new Scanner(System.in);
System.out.println("Enter a floating point value:");
num1 = scan.nextFloat();
System.out.println("Enter another floating point value:");
num2 = scan.nextFloat();
Four_Ten obj=new Four_Ten();
System.out.println(obj.calcGreater(num1, num2));
}
public double calcGreater(double a, double b){
boolean greater = false;
if (a > b){
greater = true;
}
if (b > a){
greater = false;
}
return greater;
}
}
答案 1 :(得分:1)
尝试添加关键字static
,它是boolean
而不是double
-
public static boolean calcGreater(double a, double b){
// return (a > b); /* why not a > b? */
boolean greater = false;
if (a > b){
greater = true;
}
if (b > a){
greater = false;
}
return greater;
}
答案 2 :(得分:0)
public double calcGreater(double a, double b)
不是static
方法,因此您无法从non-static
method.add static
关键字调用static
方法calcGreater()
如下
public static double calcGreater(double a, double b)
或
实例化对象和调用方法如下
Four_Ten a=new Four_Ten();
a.calcGreater(double a, double b);
不仅如此:返回类型不匹配
public double calcGreater(double a, double b){ // expected return type double
boolean greater = false;
if (a > b){
greater = true;
}
if (b > a){
greater = false;
}
return greater; // you are returning boolean
}
答案 3 :(得分:0)
创建类Four_Ten的对象,然后调用类似
的方法Four_Ten obj = new Four_Ten();
obj.calcGreater(num1,num2);
您收到错误,因为静态成员无法直接访问非静态成员。在这种情况下,main()是静态的,calcGreater()是非静态的,因此您需要一个对象来访问静态main()函数中的非静态函数calcGreater()。