开发者

non static variable called from static content, java

开发者 https://www.devze.com 2022-12-14 05:40 出处:网络
I know this question was answered before, but I cant still handle it with my code. Please can someone pointing out how can I fix it on this particular code. Id like to call trace(); but dont know wher

I know this question was answered before, but I cant still handle it with my code. Please can someone pointing out how can I fix it on this particular code. Id like to call trace(); but dont know where to call new trace. I tried different stuff from here but it does not work for me. Thank you!

package matr;

import java.util.Scanner;

final public class Matrix {

    private final int M;
    private final int N;
    private double[][] data;



    public Matrix(int M, int N) {

        this.M = M;
        this.N = N;

        data = new 开发者_C百科double[M][N];

    }

    public Matrix(double[][] data) {
        M = data.length;
        N = data[0].length;
        this.data = new double[M][N];
        for (int i = 0; i < M; i++)
            for (int j = 0; j < N; j++)
                this.data[i][j] = data[i][j];
    }

    private Matrix(Matrix A) {
        this(A.data);
    }

    public static Matrix random(int M, int N, int r) {

        Matrix A = new Matrix(M, N);
        for (int i = 0; i < M; i++) {
            for (int j = 0; j < N; j++) {
                A.data[i][j] = (Math.random() * r);
            }
        }
        return A;
    }

    public double trace() {
        // trace a = new trace();

        double t = 0;
        for (int i = 0; i < Math.min(M, N); i++) {
            t += data[i][i];
        }
        return t;
    }

    public static void main(String[] args) {

        Scanner scan = new Scanner(System.in);
        System.out.println("rows: ");
        try {
            int x = Math.abs(scan.nextInt());

            System.out.println("columns: ");
            int y = Math.abs(scan.nextInt());
            System.out
                    .println("generate: ");
            int r = scan.nextInt();

            Matrix A = Matrix.random(x, y, r);
            System.out.println("random A");

            trace();

        } catch (java.util.InputMismatchException e) {
            System.out.println("Please enter a valid int");
        }
    }
}


call A.trace()

  1. use lower-case names for variables and fields
  2. your main method is static. and your trace() method is a non-static method of the Matrix class. That means you have to call trace() on an instance of Matrix.


You are trying to call a non-static method trace() from a static method main(). Since 'main' is static it can only refer to static variables and static methods within the class. You will need to use an instance of Matrix to call trace. for example:

Matrix A = Matrix.random(x,y,r);
A.trace();


You need to call the trace() method on an instance of the type Matrix.

You could do this simply by:

A.trace();
0

精彩评论

暂无评论...
验证码 换一张
取 消