내 간단한 프로그램은 사용자에게 도시를 거의 입력하지 말 것을 요청합니다. 사용자는 다른 옵션을 선택하여 인쇄 할 수 있어야합니다.동일한 변수를 두 가지 방법으로 전역 변수로 사용하지 않으면 어떻게됩니까?
이제 이러한 값을 저장하는 메서드 (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
}
}
}
이것은 정확히 내가 원했던 것입니다. ur 대답을 받아들이기를 기다릴 수 없었습니다. 대단히 감사합니다. 여보. – Riyana