0

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

Chris
  • 664
  • 3
  • 17
Vikas Thakur
  • 422
  • 3
  • 12
  • please provide the exception logs. – Yusuf Kapasi Nov 19 '14 at 04:52
  • You are probably not entering the data in the correct order. It looks like you need to enter a String, String, then an int, 3 times. It helps to add println() statements before each `nextLine()` or `nextInt()` call so you know what type of data to enter next. – mdnghtblue Nov 19 '14 at 05:03
  • 1
    Possible duplicate of [*'Skipping nextLine() after use nextInt()'*](http://stackoverflow.com/questions/13102045/skipping-nextline-after-use-nextint). You need to call `nextLine` after the call to `nextInt`. Otherwise the program gets one `nextXXX` call ahead of you. At the point you input `R`, the programming is asking for `nextInt`. – Radiodef Nov 19 '14 at 05:05

2 Answers2

1

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.

Chris
  • 664
  • 3
  • 17
1

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
Ankur Singhal
  • 23,626
  • 10
  • 70
  • 108