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

3
  • please provide the exception logs. Commented Nov 19, 2014 at 4: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. Commented Nov 19, 2014 at 5:03
  • 1
    Possible duplicate of '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. Commented Nov 19, 2014 at 5:05

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.