这是我的代码
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 block
如果没有 try block ,这是我得到的输出
最佳答案
我的建议是始终将整行扫描为字符串,并使用解析方法将其转换为所需的数据类型。请看下面:
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");
}
}
关于java - 使用 Scanner nextLine 处理 String 时出现 InputMismatchException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38319917/