non-static variable cannot be referenced from a static context (java)
- by Greg
I ask that you ignore all logic.. i was taught poorly at first and so i still dont understand everything about static crap and its killing me.
My error is with every single variable that i declare then try to use later inside my methods... i get the non-static variable cannot~~ error
I can simply put all the rough coding of my methods inside my cases, and it works but then i cannot use recursion...
What i really need is someone to help on the syntax and point me on the right direction of how to have my methods recognize my variables at the top... like compareCount etc
thanks
public class MyProgram7 {
public static void main (String[]args) throws IOException{
Scanner scan = new Scanner(System.in);
int compareCount = 0;
int low = 0;
int high = 0;
int mid = 0;
int key = 0;
Scanner temp;
int[]list;
String menu, outputString;
int option = 1;
boolean found = false;
// Prompt the user to select an option
menu = "\n\t1 Reads file" +
"\n\t2 Finds a specific number in the list" +
"\n\t3 Prints how many comparisons were needed" +
"\n\t0 Quit\n\n\n";
System.out.println(menu);
System.out.print("\tEnter your selection: ");
option = scan.nextInt();
// Keep reading data until the user enters 0
while (option != 0) {
switch (option) {
case 1:
readFile();
break;
case 2:
findKey(list,low,high,key);
break;
case 3:
printCount();
break;
default: outputString = "\nInvalid Selection\n";
System.out.println(outputString);
break;
}//end of switch
System.out.println(menu);
System.out.print("\tEnter your selection: ");
option = scan.nextInt();
}//end of while
}//end of main
public static void readFile() {
int i = 0;
temp = new Scanner(new File("CS1302_Data7_2010.txt"));
while(temp.hasNext()) {
list[i]= temp.nextInt();
i++;
}//end of while
temp.close();
System.out.println("File Found...");
}//end of readFile()
public static void findKey() {
while(found!=true) {
while(key < 100 || key > 999) {
System.out.println("Please enter the number you would like to search for? ie 350: ");
key = scan.nextInt();
}//end of inside while
//base
if (low <= high) {
mid = ((low+high)/2);
if (key == list[mid]) {
found = true;
compareCount++;
}//end of inside if
}//end of outside if
else if (key < list[mid]) {
compareCount++;
high = mid-1;
findKey(list,low,high,key);
}//end of else if
else {
compareCount++;
low = mid+1;
findKey(list,low,high,key);
}//end of else
}//end of outside while
}//end of findKey()
public static void printCount() {
System.out.println("Total number of comparisons is: " + compareCount);
}//end of printCount
}//end of class