简体   繁体   English

Java.util.Scanner错误

[英]Java.util.Scanner Error

I am writing a program to return the future value based off some input the user gives 我正在编写一个程序,根据用户提供的一些输入返回未来值

import java.util.Scanner; //import utility package, scanner class
import java.lang.Math; //import language package, math class 
class InvestmentCalculation

{
   public static void main(String[] args) 

   {

      Scanner s = new Scanner(System.in);

      //Principle Value Input
      System.out.print("Enter principle deposit: ");
      int p = s.nextInt ();

      //Interest Rate Input
      System.out.print("Enter annual interest rate: ");
      int r = s.nextInt ();

      double fv = p * Math.pow( (1.0 + r/100), 10);  


      //operation print
      System.out.println("Your investment will be worth: " + fv);
   }
} 

When I run the program, after I type in the rate it gives me the following error: 当我运行程序时,输入速率后会出现以下错误:

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.nextInt(Scanner.java:2117)
    at java.util.Scanner.nextInt(Scanner.java:2076)
    at InvestmentCalculation.main(Addition.java:20)

This is because you are probably entering the rate as a double and the input is thus incorrect. 这是因为您可能输入的是双倍汇率,因此输入不正确。

NOTE: The InputMismatchException in the JavaDocs reads as follows: 注意: JavaDocs中InputMismatchException如下:

Thrown by a Scanner to indicate that the token retrieved does not match the pattern for the expected type, or that the token is out of range for the expected type. 由扫描程序抛出,以指示检索到的令牌与预期类型的​​模式不匹配,或者令牌超出预期类型的​​范围。

Fix via: 通过以下方式修复:

//Interest Rate Input
System.out.print("Enter annual interest rate: ");
double r = s.nextDouble();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM