gpt4 book ai didi

Java.util.Scanner 错误

转载 作者:行者123 更新时间:2023-12-02 04:33:34 25 4
gpt4 key购买 nike

我正在编写一个程序,根据用户提供的一些输入返回 future 值

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);
}
}

当我运行该程序时,输入费率后会出现以下错误:

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)

最佳答案

这是因为您输入的汇率可能是 double 的,因此输入不正确。

注意: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.

修复方式:

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

关于Java.util.Scanner 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31129677/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com