Search code examples
javaarraysobjectinputmismatchexception

Object Array in JAVA giving InputMismatchException


Code and Snap of the Exception are attached. Pls Help me out with InputMismatchException. I believe there is something wrong while entering the value at runtime

import java.util.Scanner;

class ObjectArray
{
    public static void main(String args[])
    {
        Scanner key=new Scanner(System.in);
        Two[] obj=new Two[3];

        for(int i=0;i<3;i++)
        {
            obj[i] = new Two();
            obj[i].name=key.nextLine();
            obj[i].grade=key.nextLine();
            obj[i].roll=key.nextInt();
        }

        for(int i=0;i<3;i++)
        {
            System.out.println(obj[i].name);
        }
    }
}

class Two
{
    int roll;
    String name,grade;
}

Exception


Solution

  • Instead of :

    obj[i].roll=key.nextInt();
    

    Use:

    obj[i].roll=Integer.parseInt(key.nextLine());
    

    This ensures the newline after the integer is properly picked up and processed.