2015-01-13 2 views
0

내 간단한 프로그램은 사용자에게 도시를 거의 입력하지 말 것을 요청합니다. 사용자는 다른 옵션을 선택하여 인쇄 할 수 있어야합니다.동일한 변수를 두 가지 방법으로 전역 변수로 사용하지 않으면 어떻게됩니까?

이제 이러한 값을 저장하는 메서드 (city();) 안에 배열을 선언했습니다. 그리고 각각 에 대해 사용자에게을 묻는 두 가지 방법이 있습니다 (메인 클래스에서 호출 될 예정 임). 배열 ()으로 인쇄하려면 다른 방법 (city();)에 사용 된 varibale을 사용해야합니다. 따라서 printCity() 메서드는 변수를 찾을 수 없다는 오류를 표시합니다. 게다가, 그 변수를 Global (메서드 외 외부)로 선언하면 내 경우에는 작동하지 않습니다. I인지 알 수 없습니다. 그래서 동일한 변수가 서로 다른 두 가지 방법으로 작동하도록이 문제를 해결할 수 있습니까?

내 코드 : Main 클래스 :

package city; 

import java.util.*; 

public class City { 

    public static void main(String[] args) { 
     Scanner input = new Scanner(System.in); 
     UserInput ui = new UserInput(); 

     System.out.println("    THIS PROGRAM WILL TELL YOU THE CITY YOU HAVE EVER TRAVELLED\n" 
       + "       Choose one of the following option\n\n" 
       + "       You must enter city name before printing them out!"); 

     System.out.println("1. Enter the cities you have travelled\n" 
       + "2. Print out the cities\n" 
       + "3. Exit\n" 
       + "....................\n" 
       + "...................."); 

     while (true) { 

      int userChoose = input.nextInt(); 

      switch (userChoose) { 

       case 1: 
        //call method where the program asks to enter city name 
        ui.city(); 
        break; 
       case 2: 
        //call method where the program prints out the city name 

        ui.printCity(); 
        break; 
       case 3: 
        System.exit(0); 
       default: 
        System.out.println("Invalid input! Plz try again: "); 
      } 

     } 

    } 

} 

UserInput 사용자 클래스 :

package city; 

import java.util.*; 

public class UserInput { 

    Scanner inScanner = new Scanner(System.in); 

    public void city() { 
     System.out.println("How many favourite city you have in your list?"); 
      int numOfCity = inScanner.nextInt(); 
     String[] cityInArr = new String[numOfCity]; 

     for (int i = 0; i < numOfCity; i++) { 
      System.out.println("City " + (i + 1) + ": "); 
      cityInArr[i] = inScanner.next(); 

     } 
     System.out.println("YOU ARE DONE! NOW PRINT THEM OUT"); 

    } 

    public void printCity() { 


     System.out.println(""); 
     System.out.println("These are your favorite cities: "); 
     for (int j = 0; j < numOfCity; j++) {//has an error 
      System.out.printf("%s ", cityInArr);//has an error 

     } 


    } 
} 

답변

0

'global'에 의해 UserInput 클래스의 필드로 선언한다고 가정하면 (다른 것을 의미하면 나를 수정하십시오.) 왜 그렇게하고 싶지 않은지 이해하지 못합니다.

같은 클래스의 동일한 인스턴스의 두 가지 방법 사이에 데이터를 공유 고려할 때, 필드는

... 당신이 필요로 정확히이다 나는 배열과를 위해 UserInput 사용자 클래스를 재 작성의 자유를했다 필드 (기본 클래스는 변경되지 않음). 또한 배열의 길이에 따라 결정되기 때문에 도시의 수를 지나칠 필요가 없습니다.

public class UserInput { 
    private String[] cityInArr; 

    public void city() { 
     System.out.println("How many favourite city you have in your list?"); 
     Scanner inScanner = new Scanner(System.in); 
     int numOfCity = inScanner.nextInt(); 
     cityInArr = new String[numOfCity]; 

     for (int i = 0; i < numOfCity; i++) { 
      System.out.println("City " + (i + 1) + ": "); 
      cityInArr[i] = inScanner.next(); 
     } 
     System.out.println("YOU ARE DONE! NOW PRINT THEM OUT"); 
    } 

    public void printCity() { 
     System.out.println("\nThese are your favorite cities: "); 
     for (int j = 0; j < cityInArr.length; j++) {//has an error 
      System.out.printf("%s ", cityInArr[j]);//has an error 
     } 
    } 
} 
+0

이것은 정확히 내가 원했던 것입니다. ur 대답을 받아들이기를 기다릴 수 없었습니다. 대단히 감사합니다. 여보. – Riyana

0

당신은 방법 인수로 전달할 필요가있다.

public String[] city() { 
    ... 
    return cityInArr; 
} 

public void printCity(String[] cities) { 
    ... 
} 

과 :

public void printCity(String[] cityInArr, int numOfCity) { 


     System.out.println(""); 
     System.out.println("These are your favorite cities: "); 
     for (int j = 0; j < numOfCity; j++) {//has an error 
      System.out.printf("%s ", cityInArr);//has an error 

     } 

그런 다음 city() 방법은 다음 printCity() 방법에 전달할 수있는 도시의 배열을 반환해야처럼 소리이

public static void main(String[] args) { 
    ....... 
    printCity(cityArray, numOfCity); 
    ........ 
    } 
+0

그러나 여전히 numOfCity 변수를 찾아야합니다. – Riyana

+0

두 매개 변수를 모두 전달해야합니다. 편집 내 대답 –

+0

호출 부분은 불행하게도 작동하지 않습니다. Coz는 매개 변수를 찾지 못했습니다. – Riyana

1

과 같이 호출 전화 코드에서 :

String[] cities = {}; // Empty until fetched 

... 
cities = ui.city(); 
... 
ui.printCity(cities); 

네이밍을 다시 방문 하시길 강력히 권합니다. 예를 들어, getFavoriteCities()displayCities()이 더 적절할 수 있습니다.

관련 문제