InputMismatchException when using Sacnner nextLine for String [duplicate]

别说谁变了你拦得住时间么 提交于 2020-06-13 05:55:11

问题


This is my code

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");
        }
    }
}

compiling the program gave no problem. but when executing and i try to input a string space , it takes the string as two separate strings and assigns all other values of one to be null. for eg if i enter

mike hannigan
5
6.5

The output is

mike 0 0.0
hannigan 5 6.5

i tried getting the string with only a single in.nextLine(); but that causes the string to be taken as null(Throws InputMismatchException). with try and catch block

and without the try block, this is the output i get


回答1:


My suggestion is to always scan the entire line as String and convert it to required data types using parse methods. Please see below:

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");
    }
}



回答2:


Your problem is the very common mistake in understanding Scanner.

Calling nextInt(), nextFloat(), or most other nextXxx() methods will leave the newline following the number unprocessed.

A subsequent call to any of the nextXxx() methods, other than nextLine(), will automatically skip that newline, as being whitespace between tokens.

However, nextLine() does not skip leading whitespace, so calling nextLine() after any other nextXxx() method, will return an empty string (or rather whatever is on the rest of the line following the last token).

So, when mixing nextXxx() calls with nextLine() calls, you have to flush (discard) the end of the previous line by calling nextLine() first.

This means your code should be:

Scanner in = new Scanner(System.in);
int n = in.nextInt();
in.nextLine(); // Ignore rest of line after int
student[] s = new student[n];
for (int i = 0; i < n; i++) {
    s[i] = new student();
    s[i].name = in.nextLine();
    s[i].age = in.nextInt();
    s[i].cgpa = in.nextFloat();
    in.nextLine(); // Ignore rest of line after float
}
System.out.println();
System.out.println("Name\tAge\tCGPA");
for (int i = 0; i < n; i++) {
    System.out.println(s[i].name + "\t" + s[i].age + "\t" + s[i].cgpa);
}

Better yet, do what the answer by @JaganathanNanthakumar says: Always use nextLine() and parse the number yourself.



来源:https://stackoverflow.com/questions/38319917/inputmismatchexception-when-using-sacnner-nextline-for-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!