[英]Scope of variable inside do-while loop
如果用戶在程序末尾提示時輸入“ y”或“ Y”,我試圖遍歷整個程序,但是由於變量,我收到“找不到符號-變量響應”錯誤我聲明在do-while循環內,因此我想我不能在do-while循環的情況下使用它。 如果用戶輸入“ y”或“ Y”,是否有任何方法可以解決此問題,並且仍然可以遍歷該程序? 這一切都在main方法中,而getFileRunStats是包含程序中所有其他方法的方法。
以下是相關代碼:
public static void main(String[] args) throws IOException {
System.out.println("A program to analyze home field advantage in sports.");
System.out.println();
Scanner keyboard = new Scanner(System.in);
do{
getFileRunStats(keyboard);
System.out.println("Do you want to check another data set?");
System.out.print("Enter Y or y for to analyze another file, anything else to quit: ");
String response = keyboard.nextLine();
}while(response == "Y" || response == "y");
}
您只需刪除該語句,然后將其添加到循環條件中即可。
do {
} while (keyboard.nextLine().equalsIgnoreCase("y"));
@ergonaut的回答是針對您的確切問題的最佳解決方案:
您只需刪除該語句,然后將其添加到循環條件中即可。
do {
} while (keyboard.nextLine().equalsIgnoreCase("y"));
請注意,代碼還通過使用equals
方法而不是==
運算符解決了您遇到的錯誤 。
但是,對於如何使用循環內定義的值控制do-while
循環的更通用解決方案,您有兩種選擇:
// Define variable outside, no need to initialize it
String response;
do {
// code here
response = keyboard.nextLine();
} while (response.equals("Y") || response.equals("y"));
// Use break inside an infinite loop
for (;;) { // or while (true) { ... } or do { ... } while (true)
// code here
String response = keyboard.nextLine();
if (! response.equals("Y") && ! response.equals("y"))
break;
}
只是為您的問題提供了一種更可擴展的方法,因為它允許您將來向程序中動態添加更多選項。
public static void main(String[] args) {
System.out.println("A program to analyze home field advantage in sports.");
System.out.println();
Scanner keyboard = new Scanner(System.in);
boolean quit = false;
do{
System.out.println("Do you want to check another data set?");
System.out.print("Enter Y or y for to analyze another file ");
System.out.print("Enter X to do X");
System.out.print("Enter Z to do Z");
String response = getUserInput(keyboard);
if (response.equalsIgnoreCase("X"))
doX();
else if (response.equalsIgnoreCase("Y"))
doY();
else if (response.equalsIgnoreCase("Z"))
doZ();
else
quit = true;
}while(!quit);
}
private static String getUserInput(Scanner scanner) {
return scanner.nextLine();
}
private static void doX() {
System.out.println("X");
}
private static void doY() {
System.out.println("Y");
}
private static void doZ() {
System.out.println("Z");
}
}
只需在do-while循環外聲明“ response”變量,如下所示:
String reponse = null;
do{
getFileRunStats(keyboard);
System.out.println("Do you want to check another data set?");
System.out.print("Enter Y or y for to analyze another file, anything else to quit: ");
response = keyboard.nextLine();
}while(response == "Y" || response == "y");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.