线程中的异常 "main" java.util.InputMismatchException,我不知道为什么



我正在为学校做一个项目,我的代码给了我错误:线程"main"java.util.InputMismatchException 中的异常 当我尝试两次使用分隔符输入语句时。

我已经尝试过只做一个输入行并且它可以工作,但是当我添加另一行时,它会给我错误。

Scanner input=new Scanner(System.in);
input.useDelimiter("##");
System.out.println("The delimiter is '##'");
System.out.print("Enter the name of product 1, product 2, and product 3: ");
String prod1 = input.next();
String prod2 = input.next();
String prod3 = input.next();
System.out.print("Enter the quantity of product 1, product 2, and product 3: ");
int quan1 = input.nextInt();
int quan2 = input.nextInt();
int quan3 = input.nextInt();
System.out.println(prod1+" "+prod2+" "+prod3);
System.out.println(quan1+" "+quan2+" "+quan3);

预期的结果是,如果我输入 鱼##香蕉##ice 奶油### 和 3##4##5## 然后打印 鱼香蕉冰淇淋 3 4 5

此异常由 Scanner 类的实例引发,以指示检索到的令牌与预期类型的模式不匹配,或者检索到的令牌超出范围

尝试以下输入:fish##banana##ice cream##3##4##5##

我想换行符也可能被读取,因此第一个 nextInt 失败。 也许您还想使用input.nextLine()并在 ## 处拆分字符串?

为什么要使用自定义分隔符?您可以简单地获取用新行分隔的输入。

Scanner input=new Scanner(System.in);
System.out.println("Press enter key after every input");
System.out.print("Enter the name of product 1, product 2, and product 3: ");
String prod1 = input.nextLine();
String prod2 = input.nextLine();
String prod3 = input.nextLine();
System.out.print("Enter the quantity of product 1, product 2, and product 3: ");
int quan1 = input.nextInt();
input.nextLine();
int quan2 = input.nextInt();
input.nextLine();
int quan3 = input.nextInt();
input.nextLine();
System.out.println(prod1+" "+prod2+" "+prod3);
System.out.println(quan1+" "+quan2+" "+quan3);

相关内容

最新更新