2014-11-19 2 views
0

예외의 코드와 스냅이 첨부됩니다. Pls InputMismatchException 나를 도와주세요. 나는 런타임에 값을 입력하는 동안 문제가있는 생각InputMismatchException을주는 JAVA의 객체 배열

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

+0

예외 로그를 ​​제공하시기 바랍니다. –

+0

올바른 순서로 데이터를 입력하지 않았을 수 있습니다. String, String, int를 3 번 ​​입력해야합니다. 각 nextLine() 또는 nextInt() 호출 전에 println() 문을 추가하면 다음에 입력 할 데이터 유형을 알 수 있습니다. – mdnghtblue

+1

nextInt() '*] (http://stackoverflow.com/questions/13102045/skipping-nextline-after-use-nextint) 사용 후 [*'건너 뛰기 nextLine()을 복제 할 수 있습니다. 'nextInt'를 호출 한 후에'nextLine'을 호출해야합니다. 그렇지 않으면 프로그램은 당신 앞에서'nextXXX' 호출을받습니다. 당신이'R'을 입력 할 때, 프로그래밍은 nextInt를 요구합니다. – Radiodef

답변

1

:

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

사용 :이 정수 뒤에 줄 바꿈을 보장

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

제대로 픽업되어 처리됩니다.

+0

귀하의 제안에 따라 +1 완료되었습니다. –

1

사용 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; 
} 

출력

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