2014-01-13 1 views
0

Я написал программу, которая читает количество раз, когда буквы a, e, s и t и пробелы встречаются в txt-файле, и в настоящее время он работает , но только читает первую строку txt-файла. Как заставить мою программу читать все строки в txt-файле, а затем выводить количество раз, когда эти буквы используются? Спасибо за ваше время и помощь.java txt программа чтения файлов, которая читает только первую строку txt-файла

import java.util.Scanner; 
    import java.io.FileNotFoundException; 

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

     String phrase; // a string of characters 
     int countBlank; // the number of blanks (spaces) in the phrase 
     int length;  // the length of the phrase 
     char ch;   // an individual character in the string 
     int countA; 
     int countE; 
     int countS; 
     int countT; 

     java.io.File file = new java.io.File("counting.txt"); 
     Scanner inFile = new Scanner (file); 

    Scanner scan = new Scanner(System.in); 

    phrase = inFile.nextLine(); 
    length = phrase.length(); 

      // Initialize counts 

     while (true) 
     { 
     if (phrase.equalsIgnoreCase("quit")) 

      break; 

     else 
     { 

     countBlank = 0; 
     countA = 0; 
     countE = 0; 
     countS = 0; 
     countT = 0; 

     for (int i = 0; i < length; i++) 
     { 
     if (phrase.charAt(i) == ' ') 

     countBlank++; 
     ch = phrase.charAt(i); 

      switch (ch) 
      { 
      case 'a': 
      case 'A': countA++; 
        break; 
     case 'e': 
     case 'E': countE++; 
      break; 
     case 's': 
     case 'S': countS++; 
       break; 
     case 't': 
     case 'T': countT++; 
      break; 
      } 

    } 
      System.out.println(); 
      System.out.println ("Number of blank spaces: " + countBlank); 
      System.out.println(); 

     System.out.println ("Number of A's: " + countA); 
     System.out.println(); 
     System.out.println ("Number of E's: " + countE); 
     System.out.println(); 
     System.out.println ("Number of S's: " + countS); 
     System.out.println(); 
     System.out.println ("Number of T's: " + countT); 
     break; 

     }  
    } 


    } 
    } 

ответ

1

Вы можете попробовать зацикливание на файл с while-loop.

Заменить phrase = inFile.nextLine(); с:

while(inFile.hasNextLine()) // While there are lines in the file 
    phrase += inFile.nextLine(); // Add line to 'phrase' 

Не забудьте инициализировать String phrase с пустой строкой:

String phrase = ""; 

Edit: Ваш окончательный код должен выглядеть следующим образом, с некоторыми изменениями, перечисленные в конце этого ответа.

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

    String phrase = ""; // a string of characters 
    int countBlank; // the number of blanks (spaces) in the phrase 
    int length; // the length of the phrase 
    char ch; // an individual character in the string 
    int countA; 
    int countE; 
    int countS; 
    int countT; 

    java.io.File file = new java.io.File("sample.txt"); 
    Scanner inFile = new Scanner(file); 

    while (inFile.hasNextLine()) 
     phrase += inFile.nextLine(); // Add line to 'phrase' 
    length = phrase.length(); 

    // Initialize counts 

    while (true) { 

     countBlank = 0; 
     countA = 0; 
     countE = 0; 
     countS = 0; 
     countT = 0; 

     for (int i = 0; i < length; i++) { 
      ch = phrase.charAt(i); 

      switch (ch) 
      { 
      case 'a': 
      case 'A': 
       countA++; 
       break; 
      case 'e': 
      case 'E': 
       countE++; 
       break; 
      case 's': 
      case 'S': 
       countS++; 
       break; 
      case 't': 
      case 'T': 
       countT++; 
       break; 
      case ' ': 
       countBlank++; 
       break; 
      default: 
       break; 
      } 

     } 
     System.out.println(); 
     System.out.println("Number of blank spaces: " + countBlank); 
     System.out.println(); 

     System.out.println("Number of A's: " + countA); 
     System.out.println(); 
     System.out.println("Number of E's: " + countE); 
     System.out.println(); 
     System.out.println("Number of S's: " + countS); 
     System.out.println(); 
     System.out.println("Number of T's: " + countT); 
     break; 

    } 

} 

Изменения:

  • Удаляется Scanner scan = new Scanner(System.in);, так как вы не используете его.
  • Добавлен код, который я предложил выше
  • Исключен if (phrase.equalsIgnoreCase("quit")) break;
  • Добавлено switch-case когда ch == ' '
  • Добавлено default-case, так как это считается хорошей практикой программирования.
+0

Я внесла эти изменения в программу, и он все равно возвращает то же самое. – user3188576

+0

Это работает для меня. Как выглядит ваш файл? – Christian

+0

txt файл или java-файл? – user3188576

0

Конечно, Вы должны использовать while, чтобы обернуть inFile.nextLine() производить вам строку. Но так как вы используете его только после того, как он производит только первую строку.

Попробуйте обертывание вам код с этим:

while ((phrase = inFile.nextLine()) != null) { 
    // Here code 
} 
+0

Я сделал это, и теперь программа возвращает 0s для всех букв. Почему это происходит? – user3188576

0

Вы должны прочитать следующую строку в строке «Фраза».

фразу = inFile.nextLine();

до конца цикла while.

0

Линия

phrase = inFile.nextLine(); 

из вашего цикла. Следовательно, он выполняется только один раз. добавьте его внутри цикла while

Смежные вопросы