我第一次被教导不好,所以我仍然不明白静态的一切。
我的错误是与我声明的每一个变量,然后尝试使用后面的我的方法,我得到“非静态变量不能…”错误。
我可以简单地把我的方法的所有粗略的编码在我的案例,它的工作,但后来我不能使用递归。
我真正需要的是一个人帮助语法和指向我如何让我的方法识别我的变量在顶部,如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