使用 Scanner nextLine 获取字符串时出现 InputMismatchException [重复]

2024-04-01

这是我的代码

import java.io.*;
import java.util.*;
class student
{
    String name;
    int age;
    float cgpa;
}
public class getdata
{

    public static void main(String args[]) throws IOException
    {
        Scanner in=new Scanner(System.in);
        int n;
        n=in.nextInt();
        student[] s=new student[n];
        for(int i=0;i<n;i++)
        {
            try
            {
                s[i]=new student();
                s[i].name=in.nextLine();
                in.nextLine();
                s[i].age=in.nextInt();
                s[i].cgpa=in.nextFloat();
            }
            catch(InputMismatchException e)
            {
                System.out.println(e.getMessage());
            }
        }
        System.out.println();
        System.out.println("Name\tAge\tCGPA\n");
        for(int i=0;i<n;i++)
        {
            System.out.println(s[i].name+"\t"+s[i].age+"\t"+s[i].cgpa+"\n");
        }
    }
}

编译程序没有问题。但是当执行时,我尝试输入一个字符串空格,它将该字符串作为两个单独的字符串,并将其中的所有其他值分配为空。例如,如果我输入

mike hannigan
5
6.5

输出是

mike 0 0.0
hannigan 5 6.5

我尝试只用一个字符串来获取字符串in.nextLine();但这会导致字符串被视为 null(抛出 InputMismatchException)。带有 try 和 catch 块

如果没有 try 块,这就是我得到的输出


我的建议是始终将整行​​扫描为字符串,并使用解析方法将其转换为所需的数据类型。请看下面:

public static void main(String args[]) throws IOException
{
    Scanner in=new Scanner(System.in);
    int n;
    n=Integer.parseInt(in.nextLine());
    student[] s=new student[n];
    for(int i=0;i<n;i++)
    {
            s[i]=new student();
            s[i].name=in.nextLine();
            s[i].age=Integer.parseInt(in.nextLine());
            s[i].cgpa=Float.parseFloat(in.nextLine());

    }
    System.out.println();
    System.out.println("Name\tAge\tCGPA\n");
    for(int i=0;i<n;i++)
    {
        System.out.println(s[i].name+"\t"+s[i].age+"\t"+s[i].cgpa+"\n");
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 Scanner nextLine 获取字符串时出现 InputMismatchException [重复] 的相关文章

随机推荐