Search code examples
javaexceptioninputmismatchexception

InputMismatchException when using Sacnner nextLine for String


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

with try block

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

enter image description here


Solution

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