This question already has an answer here:
How to use java.util.Scanner to correctly read user input from System.in and act on it?
                                
                                    (1个答案)
                                
                        
                4年前关闭。
            
        

运行以下代码时出现扫描仪错误:
这个怎么可能?

import java.util.Scanner;

public class ComputeLoan {
    public static void main(String[] args) {
    // Create a Scanner
    Scanner input = new Scanner(System.in);

    //Enter annual interest rate in percentage e.g., 7.25%
    System.out.print("Enter annual interest rate in, e.g., 7.25%: ");
    double annualInterestRate = input.nextDouble();

    // Obtain monthly interest rate
    double monthlyInterestRate = annualInterestRate / 1200;

    //Enter number of years
    System.out.print(
      "Enter number of years as an integer, e.g., 5: ");
    int numberOfYears = input.nextInt();

    // Enter loan amount
    double loanAmount = input.nextDouble();

    // Calculate payment
    double monthlyPayment = loanAmount * monthlyInterestRate / (1 - 1 / Math.pow(1 +
    monthlyInterestRate, numberOfYears * 12));

    double totalPayment = monthlyPayment * numberOfYears * 12;


    // Display results
    System.out.println("The monthly payment is $" + (int) (monthlyPayment * 100) / 100.0);
    System.out.println("The total payment is $" + (int) (totalPayment * 100) / 100.0);

    }
}


安慰:

Exception in thread "main" java.util.InputMismatchException
    at java.util.Scanner.throwFor(Scanner.java:864)
    at java.util.Scanner.next(Scanner.java:1485)
    at java.util.Scanner.nextDouble(Scanner.java:2413)
    at ComputeLoan.main(ComputeLoan.java:10)

最佳答案

这里 :

 System.out.print("Enter annual interest rate in, e.g., 7.25%: ");
 double annualInterestRate = input.nextDouble();


在控制台上输入值时,将其输入为7.25而不是7.25%

遵循的良好做法:
在命令行上从用户接受值时,请始终以String的形式接受它们,即input.nextLine(),然后使用parse方法将其解析为适当的类型。如果解析时发生异常,则意味着用户未正确输入输入,将其通知用户并继续。

范例:

while(true) {
      try {
            System.out.print("Enter annual interest rate in, e.g., 7.25%: ");
            double annualInterestRate = Double.parseDouble(input.nextLine());
            break;
          }
     catch(NumberFormatException nfe) {
                System.out.print("Wrong input,enter again");
            }
       }

07-24 14:51