如果我在 for 循环之外采用相同的输入,则不会显示任何错误,并且只有字符串输入显示错误,其他输入(如 double 和 int)都可以在 for 循环以及外部成功采用。
import java.util.*;
class jignasu
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int a;
String name;
double paid;
String str = sc.nextLine();
System.out.println(str);
double permonth;
a=sc.nextInt();
for(int i=0;i<a;i++)
{
name=sc.nextLine();// ====> is giving java.util.InputMismatchException
paid=sc.nextDouble();
permonth=sc.nextDouble();
System.out.println(name+" "+paid+" "+permonth);
}
}
}
最佳答案
尝试,
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a;
String name;
double paid;
String str = sc.nextLine();
System.out.println(str);
double permonth;
a = sc.nextInt();
sc.nextLine();
for (int i = 0; i < a; i++) {
name = sc.nextLine();// ====> is giving java.util.InputMismatchException
paid = sc.nextDouble();
permonth = sc.nextDouble();
sc.nextLine();
System.out.println(name + " " + paid + " " + permonth);
}
}
您的sc.nextInt()不会读取输入中的换行符。这样您的 sc.nextLine() 返回换行符。要解决这个问题,您可以在 sc.nextInt() 调用之后调用 sc.nextLine() 。或者您可以使用 sc.nextLine() 代替 sc.nextInt() 并将结果解析为 Integer。
关于java - 我的代码在 for 循环 "java.util.InputMismatchException"中输入字符串时显示错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60519612/