So I've already tried looking up what's causing this and comparing my code for any possible errors to others and I have yet to find anything else that would lead to this issue.
I'm trying to call the inner class Pair in order to store data.
Quick info about my project.
Take voting data and determine someone's political stance on it. Right now I'm just trying to parse the data. Example data
Rep1[tab]D[tab]-+-+-++---
I'm storing it as...
ArrayList<Pair<String,String>>
So rep1 is the place in the ArrayList and then D and -+-+-++--- are the pair.
But I'm having an issue with trying to instantiate the Pair class " non-static variable this cannot be referenced from a static context"
specifically
C:\Users\Stephanie\Desktop>javac DecisionTree.java
DecisionTree.java:26: error: non-static variable this cannot be referenced from a static context
Pair pair = new Pair();
^
1 error
Code:
public class DecisionTree{
public static void main(String[] args)
{
ArrayList<Pair> data = new ArrayList<Pair>();
FileReader input = new FileReader ("voting-data.tsv");
BufferedReader buff = new BufferedReader(input);
String line = null;
while((line=buff.readLine())!=null)
{
Pair pair = new Pair();
String[] array = line.split("\\t");
pair.setLabel(array[1]);
pair.setRecord(array[2]);
data.add(pair);
}
}
/**
* Private class to handle my inner data
*/
public class Pair
{
private String label;
private String record;
/**
* contructor
*@param String label, the label of the person's party
*@param String record, their voting record
*/
private Pair(String label, String record)
{
this.label = label;
this.record = record;
}
/**
* empty contructor
*/
private Pair()
{
}
/**
* get the label
*@return String label, the label of the person's party
*/
private String getLabel()
{
return label;
}
/**
* get the record
*@return String record, their voting record
*/
private String getRecord()
{
return record;
}
/**
* set the label
*@param String label, the label of the person's party
*/
private void setLabel(String label)
{
this.label=label;
}
/**
* set the record
*@param String record, their voting record
*/
private void setRecord(String record)
{
this.record=record;
}
}
}
Thanks! I feel like I'm missing something really basic, it's just been a long time since I've used Java
Non-static inner classes are associated with an instance of the enclosing class in Java. This means that an instance of class Pair
in your example belongs to a specific instance of DecisionTree
. You can only create it in the context of an instance of DecisionTree
. You can't directly create a Pair
using new Pair()
in the main()
method, because that method is static (so, it's not associated with an instance of DecisionTree
).
If you don't want this, make the inner class static
:
public class DecisionTree {
// ...
public static class Pair {
// ...
}
}