0

outclass 내에서 새 인스턴스를 선언하기 때문에 왜이 코드가 문제를 일으키는 지 이해할 수 없습니다.비 정적 변수 이것은 Java의 정적 컨텍스트에서 참조 할 수 없습니다.

다음은 문제의 해결책입니다 (UvA-103) : 103-StackingBoxes. NullPointerExceptions를의

원래 내가 얻고 있었다 런타임 오류 :

C:\Users\User\Desktop\103-StackingBoxes>java 
Main 
5 2 

Exception in thread "main" java.lang.NullPointerException 
     at Main.main(Main.java:27) 

는 그 고정,하지만 지금 나는 다음과 같은 컴파일 오류가 점점 오전 : 일반적으로 Java로 피할 수있다

C:\Users\User\Desktop\103-StackingBoxes>javac 
Main.java 
Main.java:28: error: non-static variable this cannot be referenced from a static 
context 
           boxArray[i] = new box(); 
              ^
1 error 

내가 내부 클래스를 알고를 , 그러나 나는 왜 특히 내 진술이 작동하지 않는지 모르겠다.

import java.util.*; 
import java.io.*; 
//import java.util.Arrays; 

public class Main 
{ 

    public static void main(String args[]) 
    { 

     Scanner input = new Scanner(System.in); 
     int k,n; 

     while(input.hasNext()) 
     { 
      System.out.printf("\n"); 
      k = input.nextInt(); 
      n = input.nextInt(); 

      // box boxArray[] = new box(n)[k]; 
      box[] boxArray = new box[k]; 

      for(int i =0; i< k; i++) 
      { 
       boxArray[i] = new box(); 
       //boxArray[i] = boxArray[i].box(n); 
       boxArray[i].totalDim = n; 
       for(int j =0; j < n; j++) 
       { 
        boxArray[i].dimensions[j]=input.nextInt(); 
       } 
      } 


      boxArray = sortBoxArray(boxArray); 

      int count = 1; 
      for(int i =k-1; i > 1 ; i--) 
      { 
       if(boxArray[i].doesArgBoxFitInside(boxArray[i-1])) 
        count++; 
       else 
        break; 
      } 

      System.out.printf("%d\n",count); 
      for(int i = k-count; i < k ; i++) 
      { 
       if(i == k-1) 
        System.out.printf("%d",boxArray[i].placeNumber); 
       else 
        System.out.printf("%d ",boxArray[i].placeNumber); 
      } 


     } 

    } 

    public static box[] sortBoxArray(box[] boxArray) 
    { 
     for(int i = 1; i < boxArray.length; i++) 
     { 
      for(int j = boxArray.length-1; j>=i; j++) 
      { 
       boolean skip = false; 
       for(int k = 0; k < boxArray[j].totalDim; k++) 
       { 
        if(boxArray[j].dimensions[k]<boxArray[j].dimensions[k-1]) 
        { 
         box temp = boxArray[j-1]; 
         boxArray[j-1] = boxArray[j]; 
         boxArray[j]=temp; 
        } 
       } 
      } 
     } 

     return boxArray; 
    } 


    public class box{ 

     /*******************************************Fields***********************************************/ 
     public int totalDim; 
     public int dimensions[]; 
     //The field I forgot about 
     public int placeNumber; 

     /*******************************************Methods**********************************************/ 
     public box() 
     { 
      this.totalDim = -1; 
      this.dimensions= new int[0]; 
      this.placeNumber = -1; 
     } 

     public box(int totalDim) 
     { 
      this.totalDim = totalDim; 
      this.dimensions = new int[totalDim]; 
     } 

     //public box(int totalDim, int[totalDim] dimensions) 
     public box(int totalDim, int[] dimensions) 
     { 
      this.totalDim = totalDim; 
      this.dimensions = dimensions; 
      sortDim(); 

     } 

     public void sortDim() 
     { 
      Arrays.sort(dimensions);   
     } 

     public boolean doesArgBoxFitInside(box wop) 
     { 
      if(this.totalDim != wop.totalDim) 
       return false; 
      else 
      { 
       for(int i =0; i < totalDim; i++) 
       { 
        if(this.dimensions[i]<wop.dimensions[i]) 
         return false; 
       } 
       return true; 
      } 
     } 
    } 
} 

답변

2

box은 (대문자 클래스 이름의 자바 코딩 규칙에 충실하시기 바랍니다!) 내부 클래스와 정적 코드를 볼 수없는 클래스 :

"An instance of InnerClass can exist only within an instance of OuterClass and has direct access to the methods and fields of its enclosing instance. To instantiate an inner class, you must first instantiate the outer class. Then, create the inner object within the outer object with this syntax: OuterClass.InnerClass innerObject = outerObject.new InnerClass();" (http://docs.oracle.com/javase/tutorial/java/javaOO/nested.html).

+0

난은 (는) 기본 클래스이기 때문에 또한, Main.new 상자()가 오류를 반환 ... 먼저 outerClass를 인스턴스화되어있어 방법으로 다음 혼란 스러워요. – DavidRC

+0

'box'를 정적으로 만들거나 그것을 자신의 클래스로 분해합니다. – Smutje

+0

고마워요! 이것은 많은 것을 설명하는 데 도움이됩니다! 내 코드는 이제 런타임 오류를 제공하고 있지만 지금은 이것을 이해합니다. – DavidRC

1

문제는 다음과 같습니다 귀하의 상자 클래스 @Smutje에 의해 지적 된대로 Main 클래스의 내부 클래스이며 내부 클래스는 정적 메서드에 표시되지 않습니다. 이유는 : 정적 메소드는 클래스의 인스턴스가 없더라도 실행될 수 있으며, 내부 클래스 객체는 외부 클래스의 객체가 존재할 때만 존재할 수 있기 때문에 두 문 모두 모순이됩니다. 따라서 내부 클래스는 정적 메서드에서 직접 액세스 할 수 없습니다.

수정 :

어느 쪽이든 당신은 상자 클래스는 정적 할 수 있습니다 또는 외부 클래스의 객체를 한 후 상자 클래스의 인스턴스를 만들 수 있습니다. 두 번째 솔루션

코드 :

Main obj = new Main(); 
    for(int i =0; i< k; i++) 
    { 
     boxArray[i] = obj.new box(); 
관련 문제