这是我自己编写的第一批程序之一。我正在编写一个程序来告诉你你的星座是什么,我让程序使用我导入的扫描仪方法运行,但我遇到的问题是现在我正在尝试使用检查用户输入一个 while 循环,它没有按我的预期运行,当我编译我的代码时,我遇到的错误是我的 int 类型的变量没有被初始化。我在声明它时没有指定值时写了它,我不确定我应该为它指定什么来解决这个问题。
导入java.util.Scanner;
公开课 MyStarSign {
public static void main(String[] args) {
Scanner myScanner = new Scanner(System.in); // Create a Scanner object
System.out.println("What month were you born?");
String birthMonth = "";
birthMonth= myScanner.next(); // Read user input
System.out.println("You were born in " + birthMonth + "?"); // Output user input
System.out.println("What day of the month were you born?");
int birthDay;
while (birthDay > 31) {
System.out.println("Please enter a valid day of the month");
birthDay = myScanner.nextInt();
}
这就是我的代码现在的样子 ^^
现在我尝试的解决方案:
int 生日 = myScanner.nextInt();
while (birthDay > 31) {
System.out.println("Please enter a valid day of the month");
birthDay = myScanner.nextInt();
}
这就是我试图解决的问题,尽管我在编译代码时再次遇到同样的问题
public static void main(String[] args) {
Scanner myScanner = new Scanner(System.in); // Create a Scanner object
System.out.println("What month were you born?");
String birthMonth = "";
birthMonth= myScanner.next(); // Read user input
System.out.println("You were born in " + birthMonth + "?"); // Output user input
System.out.println("What day of the month were you born?");
int birthDay;
birthDay = myScanner.nextInt();
while (birthDay > 31) {
System.out.println("Please enter a valid day of the month");
birthDay = myScanner.nextInt();
}
}
Initialize 表示它需要有一个初始值,像这样:
int birthDay = 0;
所以你唯一需要做的就是为你的变量添加一个值
编辑:试试这个代码
import java.util.Scanner;
public class MyStarSign
{
public static void main(String[] args)
{
Scanner myScanner = new Scanner(System.in); // Create a Scanner object
System.out.println("What month were you born?");
String birthMonth = "";
birthMonth= myScanner.next(); // Read user input
System.out.println("You were born in " + birthMonth + "?"); // Output user input
System.out.println("What day of the month were you born?");
int birthDay = 0;
while (birthDay > 31)
{
System.out.println("Please enter a valid day of the month");
birthDay = myScanner.nextInt();
}
}
}