2017-01-25 1 views
0

4 줄이 있지만 프로그램에서 단 한 줄만 찾습니다. 내 코드에 어떤 문제가 있습니까? 입력 파일의내 코드에서 버그로 인해 회선 계산 오류가 발생합니다. 조언을주십시오

내용 :

To be, or not to be: that is the question.

Whether 'tis nobler in the mind to suffer

The slings and arrows of outrageous fortune,

Or to take arms against a sea of troubles.

내 코드 :

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

public class wordcount{ 
    public static void main(String[] args) throws FileNotFoundException { 

    Scanner console = new Scanner(System.in); 
    System.out.print("What is the name of the file? "); 

    String file = console.nextLine(); 

    Scanner input = new Scanner(new File(file)); 

    int wordCount = 0; 
    while(input.hasNext()){ 
    String word = input.next(); 
    wordCount++; 
    } 

    int lineCount = 0; 
    while(input.hasNextLine()){ 
    String line = input.nextLine(); 
    lineCount++; 
    } 

    System.out.println("total words = " + wordCount); 
    System.out.println("total lines = " + lineCount); 

    } 

} 
+0

멋진시를 썼습니다. –

+0

프로그램이 올바른 파일을 가져 왔습니까? –

+0

그래, 올바른 파일을 얻는다. 단어 수는 나를 위해 일했습니다. 그러나 줄 수는 4 대신에 어떤 이유로 든 1을 제공합니다. – Kizzo

답변

10

첫 번째 while 루프는 전체 파일을 소모 한 다음 왼쪽 아무것도 없다 않고 마지막 개행.

while(input.hasNextLine()) { 
    String line = input.nextLine(); 
    lineCount++; 
    wordCount += line.split("\\s+").length; 
} 
+0

다음 오류가 발생합니다. "wordcount.java:19 : 오류 : 잘못된 이스케이프 문자"wordCount + = input.split ("\ s +"). length; – Kizzo

+0

@Kizzo 'split ("\\ s +")'(두 개의 백 슬래시)이어야합니다. – Andreas

+1

그리고주의 : 현재이 코드는 빈 줄을 한 단어로 계산합니다. 'wordCount' 줄을'if (! line.trim(). isEmpty())'로 바꿔서 고칠 수 있습니다. – Andreas

1

사이에 두 for-loops이 줄을 추가하는 대신, 최상위 루프 라인 카운터 만들고, 공백, 토큰 화에 각 반복 분할에서, 또는 단어의 수를 찾기 위해 라인을 스캔 :

input = new Scanner(new File(file)); /* get a new scanner to start over */ 

스캐너는 처음부터 끝까지 읽고 입력을 소모합니다. 스캐너 포인터를 파일의 시작 부분으로 재설정하는 방법이 표시되지 않습니다 (Scanner.reset()).

+0

'input.close() '를 호출하는 것을 잊지 마십시오. – Andreas

+0

gc가 처리하지 않습니까? 첫 번째 스캐너가 맞을 것 같습니다. 두 번째 ... – clearlight

+0

좋은 리소스 관리를 항상 수행해야합니다. 그렇게하면 나중에 프로그램이 복잡해지면 두 번째 자연이며 잊지 않을 것입니다. – Andreas

관련 문제