java - 我的代码在 for 循环 "java.util.InputMismatchException"中输入字符串时显示错误?

标签 java string for-loop input

如果我在 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/

相关文章:

java - 如何使用 Google appengine 项目在 Eclipse 中引用另一个项目?

php - 将字符串转换为变量

python - 加速 python 中的嵌套 for 循环/通过 numpy 数组

java - 反转 Queue<Integer> 并将其转换为 int 数组

java - 如何避免使用 spanned fromHtml 的图像?

c - 它出现在 c 中的字符串数组 (null)

string - 近似字符串匹配的具体算法代码

python - 如何使用 For 循环将 isinstance() 应用于 Python 字典中的对象

c++ - for循环到while转换

java - 不幸的是 MyApp 已经停止。我该如何解决这个问题?