gpt4 book ai didi

java - InputMismatchException:无法识别字符串

转载 作者:行者123 更新时间:2023-12-01 11:16:26 24 4
gpt4 key购买 nike

我写了下面这段Java代码。当运行它并输入任何值(定义的值,例如 latte,或任何其他值,例如 az 整数)时,我得到一个 InputMismatchException。

据我所知,此异常意味着输入类型与预期类型不匹配。我错过了什么,为什么代码不能识别字符串输入?感谢您的支持。

干杯,加博

package Lesson1;

import java.util.Scanner;

public class Coffee {

public static void main(String[] args) {

//I define the type of coffees as Strings, plus the order as String as well
String espresso = "espresso";
String americano = "americano";
String cappuccino = "cappuccino";
String latte = "latte";
String order = new String();

//I ask the user for their input
Scanner choice = new Scanner(System.in);
System.out.println("What kind of coffee would you like? We have: espresso, americano, cappuccino and latte");

//depending on the user's choice, the corresponding name is displayed; if any other string is entered, the else clause is displayed
if (order.equals(choice.next(espresso))) {
System.out.println("Your order: " + espresso);

} else if (order.equals(choice.next(americano))) {
System.out.println("Your order: " + americano);

} else if (order.equals(choice.next(cappuccino))) {
System.out.println("Your order: " + cappuccino);

} else if (order.equals(choice.next(latte))) {
System.out.println("Your order: " + latte);

} else {
System.out.println("Unfortunately we can't serve you. Have a nice day!");
}

}

}



Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at Lesson1.Coffee.main(Coffee.java:22)

最佳答案

您在默认输入中写入一次,但您尝试使用 choice.next(..) 读取多次。

一种解决方案是在 if-else 语句之前在字符串中分配您的选择,然后使用 equalsIgnoreCase 进行检查。

    //I ask the user for their input
Scanner choice = new Scanner(System.in);
System.out.println("What kind of coffee would you like? We have: espresso, americano, cappuccino and latte");

String picked = choice.next();
//depending on the user's choice, the corresponding name is displayed; if any other string is entered, the else clause is displayed
if (picked.equalsIgnoreCase(espresso)) {
System.out.println("Your order: " + espresso);

} else if (picked.equalsIgnoreCase(americano)) {
System.out.println("Your order: " + americano);

} else if (picked.equalsIgnoreCase(cappuccino)) {
System.out.println("Your order: " + cappuccino);

} else if (picked.equalsIgnoreCase(latte)) {
System.out.println("Your order: " + latte);

} else {
System.out.println("Unfortunately we can't serve you. Have a nice day!");
}

关于java - InputMismatchException:无法识别字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31775742/

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