简体   繁体   中英

class within a class in java

I'm having a bit of an issue with my homework and would like an explanation if I could get one.

Currently I'm in a Data Structures class and working on an assignment that will do a modified BinarySearch that will find a Pair of numbers to find the left most number and right most number, if there are multiples, and print out the locations. The big issue that I'm running into right now is that the teacher would like us to use a Pair class to return the two ints. I have created the Pair class within the main file and was wondering if someone could point me in the right direction on what I'm doing wrong. I'm not looking for the answer just some help to understand what I need to do and why. This is what I have got right now as far as code goes:

import java.util.*;
import java.io.*;

public class Test_BinarySearchDup{

private class Pair{
    public int left;
    public int right;
}

public static void main(String[] args) throws IOException{
    String file = args[0];
    int x = Integer.parseInt(args[1]);
    Scanner fin = new Scanner(new FileReader(file));
    int count = 0;
    while(fin.hasNext()){
        fin.nextInt();
        count++;
    }
    fin.close();

    int[] array = new int[count];

    fin = new Scanner(new FileReader(file));
    while(fin.hasNext()){
        for(int i = 0; i < array.length; i++){
            array[i] = fin.nextInt();
        }
    }
    fin.close();

    BinarySearchDup(array, x);
}

public static Pair BinarySearchDup(int[] A, int x){
    int low = 0, high = A.length - 1, mid = (low + high) / 2;
    while(low <= high){
        mid = (low + high) / 2;
        if(A[mid] == x)
            return Pair(mid);
        else if(A[mid] < x)
            low = mid + 1;
        else
            high = mid - 1;
    }
}
}

I am sending the arguments via command line, so the file name is data.txt and the example int x is 10. I thought that this was going to be like the LinkedList assignment that I recently had done where you define the class(Pair) and then you set and get the ints with data. I originally had:

private class Pair(int data){
  this.data = data; 
}

but I'm not sure as to why this wouldn't work like I would want it. Anyways that is the question I have and any help to understanding this would be so greatly appreciated

The inner class is not static which means it must be bound to an object. The main method is static. You can't call a non-static member from a static method. Mark the inner class static.

private static class Pair(int data)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM