关于小白遇到Java Cannot make a static reference to the non-static method问题的解决方法

今天在学习java 类的过程中遇到了这个问题,身为小白,在网上翻了不少大佬的博客才搞明白,这才想着自己也记录一下自己在学习过程中遇到的各种bug~~~

上图~

因为定义的函数是非静态的,那么静态main 调用函数的时候,需要实例化对象,

public class hero{
    
    public  int Max(int [][]b) {
        int max=0;
        for(int i=0;i<5;i++)
            for(int j=0;j<5;j++)
                if(b[i][j]>max)
                    max=b[i][j];
        return max;
    }
    public static void main(String[] args){
        int [][]a=new int[5][5];
        for(int i=0;i<5;i++)
            for(int j=0;j<5;j++)
                a[i][j]=(int)(Math.random()*100);
        hero Max=new hero();
        System.out.println("最大值为"+Max.Max(a));
        
    }
}

或者直接将函数定义为static ,同为静态,可以直接引用。 

 

public class hero{
    
    public static int Max(int [][]b) {
        int max=0;
        for(int i=0;i<5;i++)
            for(int j=0;j<5;j++)
                if(b[i][j]>max)
                    max=b[i][j];
        return max;
    }
    public static void main(String[] args){
        int [][]a=new int[5][5];
        for(int i=0;i<5;i++)
            for(int j=0;j<5;j++)
                a[i][j]=(int)(Math.random()*100);
        // hero Max=new hero();
        int max=Max(a);
        System.out.println("最大值为"+max);

        
    }
}

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java中,当我们尝试在静态上下文中引用非静态方法时,就会出现"Cannot make a static reference to the non-static method"的错误。这个错误通常发生在以下两种情况下: 1. 在静态方法中引用非静态方法:静态方法是属于类的,而非静态方法是属于对象的。因此,在静态方法中无法直接引用非静态方法,因为没有对象实例来调用非静态方法。 2. 在静态方法中引用非静态成员变量:同样地,静态方法是属于类的,而非静态成员变量是属于对象的。在静态方法中无法直接引用非静态成员变量,因为没有对象实例来访问非静态成员变量。 解决这个问题方法有两种: 1. 创建对象实例:如果你需要在静态方法中引用非静态方法或非静态成员变量,你可以先创建一个对象实例,然后通过该对象实例来调用非静态方法或访问非静态成员变量。 2. 将非静态方法或非静态成员变量改为静态:如果你确定在静态上下文中需要引用某个方法或成员变量,你可以将其改为静态的。这样就可以直接通过类名来引用,而不需要创建对象实例。 下面是一个示例代码,演示了如何解决"Cannot make a static reference to the non-static method"错误: ```java public class Test { private int num; public static void main(String[] args) { // 创建对象实例 Test test = new Test(); test.nonStaticMethod(); // 调用非静态方法 // 或者将非静态方法改为静态方法 staticMethod(); } public void nonStaticMethod() { System.out.println("This is a non-static method."); } public static void staticMethod() { System.out.println("This is a static method."); } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值