我正在使用Java开发一个程序,但遇到错误。该程序的目的是在if-else结构中使用嵌套的if-else结构编写while循环。
-
第 33 行有一个错误,说"可变年龄可能不会 已被初始化",即使它是在 main(( 中声明的?
-
我是否正确地将if-else结构嵌套在 while 中?
-
大括号是否正确放置?
import java.util.Scanner; public class RamosSLE32 { //Begin class public static void main(String[] args) { //Begin main() Scanner input = new Scanner(System.in); int age; String correctPassword = "MonthyPython"; char tryAgain = 'Y'; char tryAgain2 = 'Y'; String q1 = "%nWhat is the password?"; String q2 = "%nEnter your age: "; while (Character.toUpperCase(tryAgain) == 'Y') { System.out.printf(q1); String password = input.nextLine(); if (!password.equals(correctPassword)) { System.out.printf("%nInvalid password!%nDo you want to try again? Y or N."); tryAgain = input.nextLine().charAt(0); } else { if (password.equals(correctPassword)) { System.out.printf(q2); age = input.nextInt(); } { if (age > 17) { System.out.printf("%nShangri-La welcomes you to your earthly paradise!%nThank you! Have a nice day!"); } else { if (age <= 17) { System.out.printf("%nSorry, NO underaged patrons allowed!%nDo you want to try again? Y or N."); tryAgain2 = input.nextLine().charAt(0); } } } } } } // End main() } // End class
你得到variable age might not have been initialized
,因为age
是局部变量,局部变量没有获得默认值。
它们的初始值是未定义的,而不通过某种方式分配值。在使用局部变量之前,必须对其进行初始化。
有关更多详细信息,请参阅:java中的默认值和初始化