我尝试制作一个程序,用户输入变量m和b的值,然后将这些变量传递给方法linear(),打印函数" y = mx + b"使用传递的变量。 PFB代码:
import java.util.Scanner;
import java.io.*;
public class line
{
double m, b;
public void liner(double m,double b)
{
System.out.print("y = " + m + "x + " + b);
}
public static void main(String args[])
{
Scanner reader = new Scanner(System.in);
System.out.print("What is the Slope");
m = reader.nextInt();
reader.close();
System.out.print("What is the Y Intercept");
b = reader.nextInt();
reader.close();
liner (m, b);
}
}
在运行上述程序时,我收到以下错误:
/line.java:17: error: non-static variable m cannot be referenced from a static context
m = reader.nextInt();
^
/line.java:20: error: non-static variable b cannot be referenced from a
static context
b = reader.nextInt();
^
/line.java:22: error: non-static variable m cannot be referenced from a
static context
liner (m , b);
^
/line.java:22: error: non-static variable b cannot be referenced from a
static context
liner (m , b);
^
/line.java:22: error: cannot find symbol
liner (m , b);
^
symbol: method liner(double,double)
location: class line
5 errors
答案 0 :(得分:1)
您需要将m
和b
的变量声明移动到main方法中,并在static
方法上添加liner
修饰符。
变量m
和b
不在main
方法的范围内,这使得无法访问它们。在此处阅读范围:https://www.geeksforgeeks.org/variable-scope-in-java/
如果没有static
修饰符,则在liner
中调用main
方法时尚未创建{{1}}方法,这就是您收到此错误的原因。在这里阅读班级成员:https://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html