static 메소드에서 non-static 변수는 왜 참조할 수 없나요?

조회수 11489회

제가 처음부터 자바를 잘 배우지 못했습니다. 그래서 `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

1 답변

  • 좋아요

    0

    싫어요
    채택 취소하기

    클래스와 클래스의 객체 사이의 차이점을 반드시 이해하셔야 합니다. 먄약에 길에서 차를 봤다고 가정해 보세요. 차의 모델이나 차의 유형은 보이지 않았어도 그것은 차인지 아셨을 거예요. 그 이유는 눈으로 본 것과 "차"라는 클래스의 정의를 비교했기 때문이지요. 클래스는 모든 차들의 공통점을 정의한 것이랍니다. 즉, 클래스를 탬플릿으로 생각하세요. 클래스는 객체들의 공동 데이터와 기능을 정의한 것이랍니다.

    길에서 본 차는 클래스 "차"의 객체입니다. 클래스 "차"의 정의대로 길거리 차는 엔진과 휠을 가지고 있고, 사람이 그것을 운전할 수 있게하는 기능을 제공하기 때문입니다.

    클래스는 "모든 차들은 색상이 있어"라고 정의한다면 객체는 "내 색은 빨간색이야"라고 할 수 있겠지요.

    객체지향 프로그래밍의 세계에서, 클래스는 Color를 저장할 수 있는 변수인 필드를 정의합니다. 클래스를 가지고 객체를 생성하면, Color 값을 저장하기 위한 메모리가 할당되고 객체만의 Color 값을 할당하게 되는 것입니다. 이와 같은 필드들은 객체마다 고유한 데이터를 표현하기 때문에 이것을 객체에 종속적인 non-static 필드라고 합니다.

    static 필드와 메소드는 모든 객체들이 공유합니다. 그것들은 클래스에 종속적이지 객체에 종속적이지 않습니다. 보통 Integer.parseInt()와 같은 기능적인 메소드를 static 메소드로 정의합니다. 보통 상수들을 static 필드로 많이 정의합니다. 예를 들면, 차의 유형들처럼 바뀌지 않는 제한된 값을 가지는 상수들을 static 필드로 정의하는 것이지요.

    질문의 문제를 해결하기 위해서, 클래스의 객체를 생성해야 합니다. 프로그램을 실행하면서 객체들의 데이터를 저장하기 위한 메모리를 할당하기 위해서요.

    프로그램의 시작을 다음과 같이 정의해보세요.

    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
    }
    

    main()메소드는 MyProgram7 클래스의 객체를 생성하고, 생성된 객체의 메소드 (run())를 호출해서 실행하도록 구현해 보세요.

답변을 하려면 로그인이 필요합니다.

프로그래머스 커뮤니티는 개발자들을 위한 Q&A 서비스입니다. 로그인해야 답변을 작성하실 수 있습니다.

(ಠ_ಠ)
(ಠ‿ಠ)