Object Array in JAVA giving InputMismatchException

557 views Asked by At

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

2

There are 2 answers

0
Chris On BEST ANSWER

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.

0
Ankur Singhal On

use Integer.parseInt(key.nextLine());

public 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 = Integer.parseInt(key.nextLine());
    }

    for (int i = 0 ; i < 3 ; i++) {
        System.out.println("Name = " + obj[i].name + " Grade = " + obj[i].grade + " Roll = " + obj[i].roll);
    }
}

}

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

output

a
a
1
b
b
2
c
c
3
Name = a Grade = a Roll = 1
Name = b Grade = b Roll = 2
Name = c Grade = c Roll = 3