제가 처음부터 자바를 잘 배우지 못했습니다. 그래서 `static이란 개념이 잘 이해가 되지 않습니다.
변수를 선언해서 메소드 안에서 사용하려고 하는데 "non-static variable cannot..."라는 에러가 발생합니다.
아래는 에러가 발생하는 경우에 대한 메소드를 간단하게 추가한 것입니다. 위의 에러로 인해서 재귀호출이 실행되지 않습니다.
문법적인 도움과 compareCount
와 같은 변수를 메소드에서 사용하는 방법에 대한 도움을 간절히 바랍니다.
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