2016-09-26 3 views
1

저는 최근에 FileIO에 대해 배우기 시작했고 사용자가 이름과 나이를 입력하는 간단한 프로그램을 만들었습니다. 이 프로그램은 잘 컴파일,하지만 난이 프로그램을 실행하면, 다음과 같은 메시지가 얻을 :이 컴파일러 오류가 무엇을 의미하는지 확실하지 오전 누군가가 나에게 그것을 설명 할 수 있다면 감사하겠습니다NoSuchElementException이 발생하는 이유는 무엇입니까?

Exception in thread "main" java.util.NoSuchElementException 
     at java.util.Scanner.throwFor(Scanner.java:862) 
     at java.util.Scanner.next(Scanner.java:1371) 
     at FileIO.main(FileIO.java:18) 

합니다. 감사!

import java.util.*; 
import java.io.*; 

public class FileIO 
{ 
     public static void main(String args[]) 
     { 
       String sourceFile = "inputfile.txt"; 
       String destinationFile = "outputfile.txt"; 
       try{ 

         File sfile = new File(sourceFile); 
         Scanner input = new Scanner(sfile); 

         while(input.hasNext()) 
         { 
           String fname = input.next(); 
           String lname = input.next(); 
           int age = input.nextInt(); 
           System.out.println(fname + ' ' + lname + ", your age is: " + age); 

         } 
         input.close(); 

       }catch(IOException ex){ 
         System.err.println(ex); 
       } 

     } 
} 
+0

다음은 다음 사이에 다음에 오는 것입니다. 텍스트를 게시 할 수 있습니까? – serge

+0

'inputfile.txt'에 오류가 있습니다. 'String fname, String lname, int age'라는 세 개의 데이터가 모두 있는지 확인하십시오. 당신이 당신의 들판 중 하나를 가지고 있지 않기 때문에 오류가오고 그것은 주로'나이'입니다. –

답변

3

나는 당신의 입력 한 줄의이 같은 것입니다 가정합니다 :

Joe C

이 경우, next()에 대한 첫 번째 호출은 Joe를 반환하고, 두 번째는 C를 반환합니다. 지금 nextInt()으로 전화를 걸면 읽을 곳이 없습니다. 따라서 NoSuchElementException.

+0

만약 그렇다면'java.util.InputMismatchException'을 던질 것입니다. 'NoSuchElementException'은 우리가 읽으려고하는 데이터가 파일에 존재하지 않을 때 발생합니다. –

+1

@Rishal'nextInt()'에서 읽을 다음 것이 정수가 아닌 경우 (예 : "London") 'InputMismatchException'이 올 것입니다. 'NoSuchElementException'은 읽는 것이 아무것도 없을 때 온다. –

+0

@JoeC thats 내가 무슨 말을하려는 것입니까 :) –

3

이처럼 변경할 수 있습니다 :

import java.util.*; 
import java.io.*; 

public class FileIO 
{ 
    public static void main(String args[]) 
    { 
      String sourceFile = "inputfile.txt"; 
      String destinationFile = "outputfile.txt"; 
      try{ 

        File sfile = new File(sourceFile); 
        Scanner input = new Scanner(sfile); 

        while(input.hasNext()) 
        { 
          String fname = input.next(); 
          String lname = ""; 
          if (input.hasNext()) 
           lname = input.next(); 
          int age = -1; 
          if (input.hasNext()) 
           age = input.nextInt(); 
          System.out.println(fname + ' ' + lname + ", your age is: " + age); 

        } 
        input.close(); 

      }catch(IOException ex){ 
        System.err.println(ex); 
      } 

    } 
} 
1

프로그램이 잘 작동!

String 
String 
int 

및 작업 디렉토리에 존재 :

는 inputfile.txt 같은 있는지 확인합니다. 작업 디렉토리를 찾으려면 코드에 다음을 추가하십시오 :

System.out.println("Working Directory = " + System.getProperty("user.dir")); 
관련 문제