两个类,实例化问题,实例化报错

public class Paixu {

public static void main(String[] args) {

    //   Paixu px=new Paixu();

    MaoPaoSort mp=new MaoPaoSort();

//上面这里就开始报错了:No enclosing instance of type Paixu is accessible. Must qualify the allocation with an enclosing instance of type Paixu (e.g. x.new A() where x is an instance of Paixu).
}

class MaoPaoSort {
    public  void test1() {
        int a[] = { 1, 1234, 356, 123, 56346, 73, 45342342, 1, 3, 56, };

        for (int i = 0; i < a.length; i++) {

            for (int j = i + 1; j < i - 1; j++) {
                if (a[i] < a[j]) {
                    int tmp = a[i];
                    a[i] = a[j];
                    a[j] = tmp;
                    System.out.println(a[j]);
                }
            }
        }

    }


}

}

7个回答

不能在静态函数中new,把 MaoPaoSort改成静态的类

MaoPaoSort是内部类,不能再Paixu外直接new
改成

 public class Paixu {
public static void main(String[] args) {

      Paixu px=new Paixu();

    MaoPaoSort mp=px.getMPSort();

//上面这里就开始报错了:No enclosing instance of type Paixu is accessible. Must qualify the allocation with an enclosing instance of type Paixu (e.g. x.new A() where x is an instance of Paixu).
}
public MaoPaoSort getMPSort(){
        return new MaoPaoSort();
    }
class MaoPaoSort {
    public  void test1() {
        int a[] = { 1, 1234, 356, 123, 56346, 73, 45342342, 1, 3, 56, };

        for (int i = 0; i < a.length; i++) {

            for (int j = i + 1; j < i - 1; j++) {
                if (a[i] < a[j]) {
                    int tmp = a[i];
                    a[i] = a[j];
                    a[j] = tmp;
                    System.out.println(a[j]);
                }
            }
        }

    }


}
}

或者把MaoPaoSort从Paixu中移出来

应该是静态方法不可以访问非静态问题,给内部类加上Static修饰就好了,然后冒泡好像有一点点问题


public class Paixu {

public static void main(String[] args) {

    // Paixu px=new Paixu();

    MaoPaoSort mp = new MaoPaoSort();
    mp.test1();

    // 上面这里就开始报错了:No enclosing instance of type Paixu is accessible. Must
    // qualify the allocation with an enclosing instance of type Paixu (e.g.
    // x.new A() where x is an instance of Paixu).
}

static class MaoPaoSort {
    public void test1() {
        int a[] = { 1, 1234, 356, 123, 56346, 73, 45342342, 1, 3, 56, };

        for (int i = 0; i < a.length-1; i++) {
            for (int j = 0; j < a.length-i-1; j++) {
                if (a[j] < a[j+1]) {
                    int tmp = a[j];
                    a[j] = a[j+1];
                    a[j+1] = tmp;

// System.out.println(a[j]);
}
}
}
for (int i : a) {
System.out.println(i);
}
}
}
}

1.内部类静态化
2.把内部类拿出来

Paixu.MaoPaoSort mp=new Paixu.MaoPaoSort();

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐