2016-10-22 4 views
0

내가 txt 파일을 입력하고을, 여기에이 코드를 실행 단축 버전없음 라인이 발견되지 않음 자바

10 
"Alexander McCall Smith" "No. 1 Ladies' Detective Agency" 

입니다 :

Scanner in = new Scanner(new File(newFile + ".txt")); 
int size = in.nextInt(); 
String inputLine = in.nextLine(); 

크기가 10 인 끝을하지만, inputLine는 수신 끝 아무것도. 내가 단서가 없다 inputLine.에 삽입하려고 무엇 자바 내가 디버거에 갔다

Exception in thread "main" java.util.NoSuchElementException: No line found. 

오류를 얻을하고 위치에 문자열을 말한다 (-1, -1) 왜, 내가 50 + 선이 알고있다 10시 이후의 텍스트. in.next()을 실행했는데 정상적으로 작동했습니다. 아무도 이유를 아나요?

은 나뿐만 아니라이 코드를 실행 :

inputLine.trim(); 
int posn = inputLine.indexOf('\"'); 
int nextPosn = inputLine.indexOf('\"',posn + 1); 
String author = inputLine.substring(posn, nextPosn); 
+0

당신이'hasNextLine'으로 확인 있습니까 : 당신의 코드에서 그 다음 발견되지 않는 경우 인덱스가 -1이 될 것이라고 "/"기호 검색 그래서 당신은뿐만 아니라 이러한 경우를 처리한다, 여기에 예입니다 ? – Li357

+0

내가 할 때 그냥 건너 뜁니다. 나는 그것이 사실이라는 것을 알고있다. 다음 라인은 내가 가지고있는 100 라인 중 2 라인에 불과하다. 나는 말 그대로 실마리가 없습니다, 그것은 처음으로 그런 실수가 나에게 일어난 일이고 나는 어리 석다. – TeenCoder

+0

@AndrewLi가 말한 것처럼, 잠시 후 hasNextLine으로 확인하거나 .. then continue –

답변

2

앤드류 리 바로이있다. nextInt으로 전화를 걸면 회선을 사용하지 않으므로 첫 번째 회선에 여전히 "10"이 표시됩니다.

public static void main(String[] args) throws FileNotFoundException { 
    Scanner in = new Scanner(Test.class.getResourceAsStream("input.txt")); 
    int size = in.nextInt(); 
    String inputLine = in.nextLine(); 
    System.out.println(size); // prints "10" 
    System.out.println(inputLine); // prints nothing 

    inputLine.trim(); 
    int posn = inputLine.indexOf('\"'); 
    int nextPosn = inputLine.indexOf('\"', posn + 1); 
    String author = inputLine.substring(posn, nextPosn); // Throws: "java.lang.StringIndexOutOfBoundsException: String index out of range: -1" 
} 

당신이 두 번 연속 nextLine를 호출한다면, 당신은 "알렉산더"라인을 얻을 것입니다.

(나는 당신이 NoSuchElementException을 받고있어 아무 생각이 없다. 그것은 당신의 프로그램에서 다른 곳에서해야합니다.)

+0

맞아요. 그래서 "더미"문자열을 만들었고 .nextLine()을했는데, 이후에 내 모든 문제를 해결했습니다.고마워, 그게 그냥 큰 brainfart 것 같아요. – TeenCoder

+0

걱정하지 않아도 파일 작업은 실망 스럽습니다. – DavidS

+0

@TeenCoder 더미 문자열이 필요 없습니다. 'nextLine'을 호출하면 새 행을 넘어서 스캐너가 진행되어 작동합니다. – Li357

0

당신이 토큰을 적절하게 라인의 종료를 처리하지 않는 경우 궁금해. Scanner # next ###() (nextLine 제외)을 사용하고 사용자가 enter 키를 누를 때와 같이 줄의 끝 부분에 도달하는 경우가 종종 있습니다. 줄 끝의 토큰을 처리하지 않으면 스캐너를 막을 수 있습니다 물체가 적절하게 작용하지 못하게한다. 이 문제를 해결하려면이 토큰을 처리해야 할 때 Scanner # nextLine()을 호출하십시오.

아래 게시물에 자세한 설명이 나와 있습니다. Scanner is skipping nextLine() after using next(), nextInt() or other nextFoo() methods

0

파일에 항목이 여러 개인 경우 각 줄을 반복하여 처리해야합니다.

public static void main(String[] args){ 
    Scanner in = null; 
    int lines; 
    int size; 
    String inputLine; 
    int posn, nextPosn; 

    try { 
     in = new Scanner(new File("testFile.txt")); 
    } 
    catch(IOException e){ 
     System.err.print("File read error: "+e.getMessage()); 
     System.exit(1); 
    } 

    lines = 0; 
    // Iterate over the lines in the file 
    while(in.hasNext()){ 
     inputLine = in.nextLine(); 
     System.out.println(inputLine); 
     inputLine = inputLine.trim(); 
     if(lines == 0){ 
      // If you know that next line is an integer 
      size = Integer.parseInt(inputLine); 
     } 
     posn = inputLine.indexOf('\"'); 
     nextPosn = inputLine.indexOf('\"',posn + 1); 
     if(posn >=0 && nextPosn >=0) { 
      String author = inputLine.substring(posn, nextPosn); 
     } 
     lines++; 
    } 
} 
관련 문제