views:

662

answers:

5

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
A: 

To be able to access them from your static methods they need to be static member variables, like this:

public class MyProgram7 {
  static Scanner scan = new Scanner(System.in);
  static int compareCount = 0;
  static int low = 0;
  static int high = 0;
  static int mid = 0;  
  static int key = 0;  
  static Scanner temp;  
  static int[]list;  
  static String menu, outputString;  
  static int option = 1;  
  static boolean found = false;

  public static void main (String[]args) throws IOException {
  ...
invariant
+2  A: 

You must understand the difference between a class and an instance of that class. If you see a car on the street, you know immediately that it's a car even if you can't see which model or type. This is because you compare what you see with the class "car". The class contains which is similar to all cars. Think of it as a template or an idea.

At the same time, the car you see is an instance of the class "car" since it has all the properties which you expect: There is someone driving it, it has an engine, wheels.

So the class says "all cars have a color" and the instance says "this specific car is red".

In the OO world, you define the class and inside the class, you define a field of type Color. When the class is instantiated (when you create a specific instance), memory is reserved for the color and you can give this specific instance a color. Since these attributes are specific, they are non-static.

Static fields and methods are shared with all instances. They are for values which are specific to the class and not a specific instance. For methods, this usually are global helper methods (like Integer.parseInt()). For fields, it's usually constants (like car types, i.e. something where you have a limited set which doesn't change often).

To solve your problem, you need to instantiate an instance (create an object) of your class so the runtime can reserve memory for the instance (otherwise, different instances would overwrite each other which you don't want).

In your case, try this code as a starting block:

public static void main (String[] args)
{
    try
    {
        MyProgram7 obj = new MyProgram7 ();
        obj.run (args);
    }
    catch (Exception e)
    {
        e.printStackTrace ();
    }
}

// instance variables here

public void run (String[] args) throws Exception
{
    // put your code here
}

The new main() method creates an instance of the class it contains (sounds strange but since main() is created with the class instead of with the instance, it can do this) and then calls an instance method (run()).

Aaron Digulla
A: 

I will try to explain the static thing to you. First of all static variables do not belong to any particular instance of the class. They are recognized with the name of the class. Static methods again do not belong again to any particular instance. They can access only static variables. Imagine you call MyClass.myMethod() and myMethod is a static method. If you use non-static variables inside the method, how the hell on earth would it know which variables to use? That's why you can use from static methods only static variables. I repeat again they do NOT belong to any particular instance.

Petar Minchev
A: 

Static fields and methods are connected to the class itself and not it's instances. If you have a class A, a 'normal' method b and a static method c and make an instance a of your class, the the call to A.c() and a.b() is valid. Method c() has so no idea, which instance is connected, so it cannot use non-static fields.

The solution for you is, that you make your fields static or make your methods non-static. You main could be look like this then:

class Programm {
  public static void main(String[] args){
    Programm programm = new Programm();
    programm.start()
  }
  public void start(){
    // can now access non-static fields
  }
}
Mnementh
A: 
  • The first thing is to know the difference between an instance of a class, and the class itself. A class models certain properties, and the behaviour of the whole in the context of those properties. An instance will define specific values for those properties.

  • Anything bound to the static keyword is available in the context of the class rather than in the context of an instance of the class

  • As a corollary to the above

    1. variables within a method can not be static
    2. static fields, and methods must be invoked using the class-name e.g. MyProgram7.main(...)
  • The lifetime of a static field/method is equivalent to the lifetime of your application

E.g. Say, car has the property colour, and exhibits the behaviour 'motion'. An instance of the car would be a Red Volkswagen Beetle in motion at 25kmph.

Now a static property of the car would be the number of wheels (4) on the road, and this would apply to all cars.

HTH

Everyone