首页 > 解决方案 > 解决获取 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");
    }
}

}

标签: javaif-statement

解决方案


问题:这里您正在从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.");
    }
}

修改:

  1. 添加Double IQ = iqInput.nextDouble(); and Double termMean = termMeanInput.nextDouble();.

  2. IQ and termMeanif-else 语句中使用的值。


推荐阅读