gpt4 book ai didi

java - 线程 "main"java.util.InputMismatchException 中出现异常,扫描仪错误

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

在练习 Java 时,我被一个错误困住了好几个小时。当我输入带小数点的价格时,出现此错误

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 grocerystore.GroceryStore.main(GroceryStore.java:19)
C:\Users\aslan\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53:

我的代码:

package grocerystore;
import java.util.Scanner;
/**
*
* @author aslan
*/
public class GroceryStore {

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
double [] prices = new double [5];
Scanner in = new Scanner(System.in);
System.out.println("Enter 5 prices: ");
prices[0] = in.nextDouble();
prices[1] = in.nextDouble();
prices[2] = in.nextDouble();
prices[3] = in.nextDouble();
prices[4] = in.nextDouble();
double total = prices[0] + prices[1] + prices[2] + prices[4];
System.out.printf("the tot1al of all 5 items is:$%5.2f" +total);
}
}

谁能帮忙???

最佳答案

除了 in.nextDouble() 的数字或句号之外的任何内容都会抛出 InputMismatchException。因此请尽量确保只输入数字和句号。

此外,printf() 的参数是格式字符串,然后是参数。由于您提供的 String 中有一个格式说明符,因此它必须有一个要匹配的参数。所以正确的语法是.out.printf("所有 5 项的总数为:$%5.2f", 总计);

此外,我注意到您错过了价格[3]。一个可行的解决方案:

        double[] prices = new double[5];

Scanner in = new Scanner(System.in);
System.out.println("Enter 5 prices: ");

prices[0] = in.nextDouble();
prices[1] = in.nextDouble();
prices[2] = in.nextDouble();
prices[3] = in.nextDouble();
prices[4] = in.nextDouble();

double total = prices[0] + prices[1] + prices[2] + prices[3] + prices[4];

System.out.printf("the tot1al of all 5 items is:$%5.2f", total);


Output:

Enter 5 prices:
.0
.1
.2
.3
.4
the tot1al of all 5 items is:$ 1.00

关于java - 线程 "main"java.util.InputMismatchException 中出现异常,扫描仪错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50515530/

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