java - 解决获取 Scanner 输入时的 if/else 问题
问题描述
我创建了两个 Scanner 对象,蚂蚁得到了它们。但是当获取输入完成时,if/else 代码不起作用。问题出在哪里?主要问题是关于“InputMismatchException”。我想当用户输入除双精度以外的值时,程序会显示“请输入正确的格式”。我想用这两个输入处理这个异常。什么是正确的代码?你能解释一下并写正确的代码吗?tnx。
import java.util.Scanner;
public class NestedIf {
public static void main(String[] args) {
Scanner iqInput=new Scanner(System.in);
System.out.println("Please enter your IQ: ");
iqInput.nextDouble();
Scanner termMeanInput=new Scanner(System.in);
System.out.println("Please enter your term mean: ");
termMeanInput.nextDouble();
if(iqInput.hasNextDouble() && termMeanInput.hasNextDouble()){
if(iqInput.nextDouble()>110 && termMeanInput.nextDouble()>18){
System.out.println("You got 30 percent discount.");
}else if(iqInput.nextDouble()>100 && termMeanInput.nextDouble()>17){
System.out.println("You got 20 percent discount.");
}else if(iqInput.nextDouble()<100 && termMeanInput.nextDouble()<17){
System.out.println("You have no discount");
}
}else{
System.out.println("Please enter the right format");
}
}
}
解决方案
问题:这里您正在从iqInput.nextDouble();
和读取值termMeanInput.nextDouble();
。但是,您没有将它们的值存储在任何变量中以便在 if 语句中使用它。
试试这个:
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
try {
System.out.print("Please enter your IQ: ");
Double IQ = s.nextDouble(); // Modification
System.out.print("Please enter your term mean: ");
Double termMean = s.nextDouble();
if(IQ<100 && termMean<17) {
System.out.println("You have no discount");
} else if(IQ>110 && termMean>18) {
System.out.println("You got 30 percent discount.");
} else {
System.out.println("You got 20 percent discount.");
}
}
catch(InputMismatchException e) {
System.out.println("Please enter the right input format.");
}
}
修改:
添加
Double IQ = iqInput.nextDouble(); and Double termMean = termMeanInput.nextDouble();
.IQ and termMean
if-else 语句中使用的值。
推荐阅读
- javascript - 如何在 am4charts 中添加单个系列项目符号?
- apache-spark - 带有 HDP 2.6 堆栈的 Apache spark 3.0
- r - 从 nlsModel 对象求解特定 x 值
- python - 右键单击特定 x 和 y 坐标处的元素 - Selenium Python
- mysql - 如何在 SELECT 查询 MySQL 中编写子查询
- php - 如何在 Nginx 上添加自定义 PHP 位置
- html - SVG 图像显示我无法移除的细边框
- julia - 获取已为通用函数编译的所有函数签名的列表
- python-3.x - 如何检索python json对象值
- mongodb - Mongoose 模型数组位于对象末尾的另一个数组中,而不是数组的开头;)令人困惑的问题