do-while循环中变量的范围 [英] Scope of variable inside do-while loop
问题描述
如果用户在程序末尾提示时输入 y或 Y,我试图遍历整个程序,但出现找不到符号-变量响应错误由于我声明的变量位于do-while循环内,因此我想我不能在do-while循环的条件下使用它。如果用户输入 y或 Y,有什么方法可以解决此问题,并且仍然可以遍历该程序?这一切都在main方法中,而getFileRunStats是包含程序中所有其他方法的方法。
I'm trying to loop through an entire program if the user inputs "y" or "Y" when they are prompted at the end of the program, but I'm getting a "cannot find symbol - variable response" error since the variable I declared is inside the do-while loop, therefore I suppose I can't use it in the condition of the do-while loop. Is there any way to get around this problem and still be able to loop through the program if the user inputs a "y" or "Y"? This is all in the main method and getFileRunStats is the method that contains all other methods from the program.
以下是相关代码:
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");
}
推荐答案
您可以删除该语句,并将其添加到循环条件中。
You can just remove the statement, and add it to the loop condition.
do {
} while (keyboard.nextLine().equalsIgnoreCase("y"));
这篇关于do-while循环中变量的范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!