这是我的代码:
package Random;
import java.util.Scanner;
public class SwitchMonth {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter Year: ");
int year = in.nextInt();
System.out.println("Enter month: ");
String month = in.nextLine();
//String month = ""
switch (month) {
case "january":
case "march":
case "may":
case "july":
case "august":
case "october":
case "december":
System.out.println("No. of days: 31");
break;
case "april":
case "june":
case "september":
case "november":
System.out.println("No. of days: 30");
break;
case "february":
if ((year % 4 == 0) && !(year % 100 == 0) || (year % 400 == 0))
System.out.println("No. of days: 29");
else
System.out.println("No. of days: 28");
break;
default:
System.out.println("Wrong month entered.");
break;
}
in.close();
}
}
输出:
Enter year: 2000
Enter month:
Wrong month entered.
程序在不输入月份的情况下终止。 如果我对月份名称进行硬编码,那么它工作正常,但是当我从控制台获取输入时,它会以上述输出终止。我相信问题出在 Scanner 对象上。 如果我使用另一个 Scanner 对象一个月,那么它工作正常。
所以我的问题是:我可以使用相同的扫描仪对象来接受 int 输入然后字符串输入吗? 如果不是那为什么??
感谢所有答案。提前致谢。
最佳答案
nextInt()
在输入年份后不会消耗 ENTER,因此 nextLine()
会消耗它,留下一个空的字符串。解决这个问题的一种方法是始终使用 nextLine()
:
int year = Integer.valueOf(in.nextLine());
或者,您可以在使用 int
后使用 another nextLine()
:
int year = in.nextInt();
in.nextLine(); // To get rid of the additional \n
关于java - 同一 Scanner 对象可以接受不同数据类型的输入吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26441120/