I don't understand why does this code give me issues since I am declaring new instances within the outclass.
Here is my solution for the problem (UvA-103): 103-StackingBoxes.
Originally I was getting runtime errors of NullPointerExceptions:
C:\Users\User\Desktop\103-StackingBoxes>java Main 5 2 Exception in thread "main" java.lang.NullPointerException at Main.main(Main.java:27) I fixed that, but now I am getting the following compilation error:
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 I know inner classes are typically avoided in Java, but I do not get why in particular do my statements not work.
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; } } } }