“无法从静态上下文中引用非静态变量,非静态方法”原因及解决

1.原因

(1)用static修饰的方法为静态方法,修饰变量则为静态变量,又分别叫做类方法或者类变量。这些从属于类,是类本身具备的,没有实例也会存在。

(2)而非静态方法和变量的存在依赖于对象,是对象的属性,需要先创建实例对象,然后通过对象调用。

所以怎么能轻易地 在一定存在的静态上下文中,引用不一定存在的非静态变量or方法 呢?

2.解决

下例提供两种解决方法:

package com.Homework01;
import java.util.*;

//对给定的四个整数从大到小排列,这里用了冒泡排序,排序算法详见下一篇博文。

public class Homework01 {
    public static void main(String[] args){
        Scanner scan = new Scanner(System.in);
        int[] numbers = new int[4];
        System.out.println("Please input 4 numbers:");
        for (int i = 0; i < 4; i++)
            numbers[i] = scan.nextInt();
        //方法一:如下,实例化一个对象sort,然后才能在静态方法中调用非静态方法Sort()!
        Homework01 sort = new Homework01();
        sort.Sort(numbers);
    }
    //方法二:直接将Sort声明为静态,即 static void Sort(int[] numbers)... 
    void Sort(int[] numbers){
        for (int j = 0; j < numbers.length-1; j++) {
            for (int i = 0; i < numbers.length - 1 - j; i++) {
                int temp = numbers[i];
                if (numbers[i] < numbers[i + 1]) {
                    numbers[i] = numbers[i + 1];
                    numbers[i + 1] = temp;
                }
            }
        }
        for(int i = 0; i<numbers.length; i++)
            System.out.println(numbers[i]);
    }
}

猜你喜欢

转载自blog.csdn.net/qq_32732581/article/details/82860549