我的Java程序中的错误,y = mx + b with method

时间:2017-12-26 14:33:05

标签: java

我尝试制作一个程序,用户输入变量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

1 个答案:

答案 0 :(得分:1)

您需要将mb的变量声明移动到main方法中,并在static方法上添加liner修饰符。

变量mb不在main方法的范围内,这使得无法访问它们。在此处阅读范围:https://www.geeksforgeeks.org/variable-scope-in-java/

如果没有static修饰符,则在liner中调用main方法时尚未创建{{1}}方法,这就是您收到此错误的原因。在这里阅读班级成员:https://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html