java - 扫描仪输入/输出格式错误
问题描述
此代码返回正确的最终结果,但控制台中输入和输出的格式不正确。
这是期望的结果:
Type your age: hello
Type your age: ?
Type your age: 3.14
Type your age: 25
Type your GPA: a
Type your GPA: bcd
Type your GPA: 2.5
age = 25, GPA = 2.5
该程序会分别询问年龄和 GPA,直到它得到正确的输入,然后打印它们。
这是我得到的:
Type your age: hello
Type your age: ?
Type your age: 3.14
25
Type your GPA: a
Type your GPA: bcd
2.5
age = 25, GPA = 2.5
如您所见,结果相同,但格式不正确。我确信这与我使用扫描仪对象的方式有关,但我对扫描仪的理解目前是有限的。
这是裸代码:
Scanner console = new Scanner(System.in);
System.out.print("Type your age: ");
console.next();
while (!console.hasNextInt()) {
System.out.print("Type your age: ");
console.next();
}
int age = console.nextInt();
System.out.print("Type your GPA: ");
console.next();
while (!console.hasNextDouble()) {
System.out.print("Type your GPA: ");
console.next();
}
double gpa = console.nextDouble();
System.out.println("age = " + age + ", GPA = " + gpa);
解决方案
完全删除console.next()
之前的while循环,你不需要它。然后,您将获得所需的输出。当您拥有 时console.next()
,您正在寻找并返回另一个完整的令牌,在您的情况下您根本不需要。
Scanner console = new Scanner(System.in);
System.out.print("Type your age: ");
while (!console.hasNextInt()) {
System.out.print("Type your age: ");
console.next();
}
int age = console.nextInt();
System.out.print("Type your GPA: ");
while (!console.hasNextDouble()) {
System.out.print("Type your GPA: ");
console.next();
}
double gpa = console.nextDouble();
System.out.println("age = " + age + ", GPA = " + gpa);
推荐阅读
- junit - 使用 ant 使用 mpirun 运行单元测试
- c# - 如何修复 xamarin 表单中的“打开失败:errno 13”异常
- marklogic - 克隆我的应用程序最方便的方法是什么?
- cassandra - 卡桑德拉墓碑太多
- python - 尝试在 MacOS 中运行 python 文件时如何修复非法指令:4?
- powershell - 阻止移动/删除文件夹,但不阻止子文件夹或文件
- android - 即使应用程序在棉花糖中被杀死,如何避免杀死后台服务?
- mysql - 删除 FROM Kunden_ansprechpartner as a left join Ansprechpartner as b on a.AnsPaID=b.AnsPaID where b.AnsPaID=400 and Kdnr = 10088
- excel - VBA 打印 Outlook 项目
- php - 数组多维搜索返回所有多个键