2014-12-14 1 views
1

은 외부 파일의 내용을 읽고 단어 수, 3 자 단어 수 및 전체 비율을 결정해야하는 숙제를위한 코드입니다. 나는 그 부분을 잘 처리했지만 위의 정보를 표시하기 전에 외부 파일의 내용을 인쇄해야합니다.외부 파일의 내용 인쇄 아래의

public class Prog512h 
{ 
    public static void main(String[] args) 
    { 
    int countsOf3 = 0; 
    int countWords = 0; 

    DecimalFormat round = new DecimalFormat("##.00"); // will round final value to two decimal places 

    Scanner poem = null; 
    try 
    { 
     poem = new Scanner (new File("prog512h.dat.txt")); 
    } 
    catch (FileNotFoundException e) 
    { 
     System.out.println ("File not found!"); // returns error if file is not found 
     System.exit (0); 
    } 

    while (poem.hasNext()) 
    { 
     String s = poem.nextLine(); 
     String[] words = s.split(" "); 
     countWords += words.length; 
     for (int i = 0; i < words.length; i++) 
     { 
      countsOf3 += words[i].length() == 3 ? 1 : 0; // checks for 3-letter words 
     } 
    } 

    while(poem.hasNext()) 
    {  
     System.out.println(poem.nextLine()); 
    } 
    System.out.println(); 
    System.out.println("Number of words: " + countWords); 
    System.out.println("Number of 3-letter words: " + countsOf3); 
    System.out.println("Percentage of total: " + round.format((double)((double)countsOf3/(double)countWords) * 100.0)); // converts value to double and calculates percentage by dividing from total number of words 
    } 

    } 

while(poem.hasNext()) 
{  
    System.out.println(poem.nextLine()); 
} 

이 외부 파일의 내용을 인쇄하도록되어 : 다음은 내 현재 코드입니다. 그러나 그렇지 않습니다. 이전 while 루프 이전에 이동하려고하면 인쇄되지만 단어, 3 글자 단어, 백분율 등의 인쇄 된 값이 엉망이됩니다. 여기에 어떤 문제가 있는지는 잘 모르겠습니다. 누군가 도움을 줄 수 있습니까?

미리 감사드립니다.

+0

신속한 제안에 감사드립니다. 방금 행운을 들이지 않고 구현하려고했습니다. 내용이 여전히 인쇄되지 않습니다. : – Blackout621

답변

1

스캐너가 파일을 다시 읽으려고하지만 하단에 있으므로 읽을 줄이 더 없습니다.

옵션 1

같은 파일의 새 Scanner 객체를 만든 다음 해당 파일에 while 루프를 호출 (다시 처음부터 시작하는) (작동,하지만 좋은 디자인) : 두 가지 옵션이 있습니다 .

Scanner poem2 = null; 
try 
{ 
    poem2 = new Scanner (new File("prog512h.dat.txt")); 
} 
catch (FileNotFoundException e) 
{ 
    System.out.println ("File not found!"); // returns error if file is not found 
    System.exit (0); 
} 

while(poem2.hasNext()) 
{  
    System.out.println(poem2.nextLine()); 
} 

옵션 2

더 좋은 옵션은 당신이 그것을 읽고 각 라인을 표시하는 것이 이미 존재 while 루프에 여분의 줄을 추가하여 수행 할 수 있습니다.

while (poem.hasNext()) 
{ 
    String s = poem.nextLine(); 
    System.out.println(s); // <<< Display each line as you process it 
    String[] words = s.split(" "); 
    countWords += words.length; 
    for (int i = 0; i < words.length; i++) 
    { 
     countsOf3 += words[i].length() == 3 ? 1 : 0; // checks for 3-letter words 
    } 
} 

이것은 오직 하나의 Scanner 객체를 필요로하며 훨씬 효율적으로 파일을 읽을 수 있습니다.

+0

내가 돌아가서 내 코드를 다시하고 싶으면 시간 제약 때문에 과제가 끝나기 전에 그렇게하지 못하게됩니다. 옵션 하나를 시도하고 트릭을 실행 했으므로 희망을 갖고 코드를 다시 실행할 수 있습니다. 정보 제공의 목적. 고마워, 친구 야! – Blackout621

+1

@ Blackout621 두 번째 옵션은 첫 번째 옵션보다 실제로 구현하는 것이 더 빠를 것입니다. 좀 더 협박하는 소리가 들립니다. 훨씬 스타일이 좋으므로 확인해보십시오. – carloabelli

+0

아 ... 그게 훨씬 간단합니다. 나는 그것을 사용할 것이라고 생각했다. 대신 사용하겠다! 다시 한번 감사한다. :) – Blackout621