2013-10-27 4 views
0

Я получаю ошибки в своем коде, когда он возвращает количество слов в предложении. У меня есть переменная, которая содержит ограничения для предложений. Текстовый файл, который я читаю, приведен ниже. Спасибо за любую помощь.Ошибки возвращают количество слов в предложении

Текст читается в: «один !!!!! два !!!!! три: Баба? Ого! Бубу и бебе».

WORD_DELIMETERS = ".:;? !, ''";

Выходной Я получаю:

Есть 9 слов в файле.

В файле 14 гласных.

В файле содержатся 6 предложений.

Должно быть возвращено 8 слов, а не 9, предложения и гласные правильны.

//START of count the words******************************************** 
int wordCounter= 0; 
int last_Index=0; 
for(int i=0;i<myFile.length()-1;i++){ 
    for(int j=0;j<WORD_DELIMETERS.length()-1;j++){ 
     if(myFile.charAt(i)==WORD_DELIMETERS.charAt(j)){ 
       if(myFile.charAt(i+1) !=' '){ 
        if(last_Index!=i-1){ 
         wordCounter++; 
        } 
        last_Index=i; 

       } 
      } 
     } 
} 
// END of count the words***********************************************  
+7

Отлаживайте свой код, и вы узнаете, почему. – Maroun

+1

Мы здесь не для того, чтобы делать домашнее задание для вас. Итак, покажите, что вы прилагаете усилия для решения проблемы, тогда вы получите помощь. –

+0

Такой сложный способ подсчета слов ... Взгляните на 'String # split'. – m0skit0

ответ

0

Вы не считаете первое слово. Итак, вы должны запустить счетчик с 1, если строка не пуста.

Я использую его:

String myFile = "one!!!!! two!!!!! three: Baba? Oho! Bubu and bebe."; 
    String pattern ="[.|:|;|?|!|,|'| ]"; 
    int counter = 0; 
    for(String word : myFile.split(pattern)) { 
     if(word.length()!=0)counter++; 
    } 
    System.out.println("Words: "+counter); //print Words: 8 

Вы можете изменить свой счетчик:

public static int yourCounter(String myFile) { 
    if(myFile.length()==0)return 0; 
    String WORD_DELIMETERS = ".:;?!,' ]"; 
    int wordCounter= WORD_DELIMETERS.contains(myFile.charAt(0)+"")?0:1; 
    int last_Index=0; 
    for(int i=0;i<myFile.length()-1;i++){ 
     for(int j=0;j<WORD_DELIMETERS.length()-1;j++){ 
      if(myFile.charAt(i)==WORD_DELIMETERS.charAt(j)){ 
        if(myFile.charAt(i+1) !=' '){ 
         if(last_Index!=i-1){ 
          wordCounter++; 
         } 
         last_Index=i; 

        } 
       } 
      } 
    } 
    return wordCounter; 
} 

я использую раскол и регулярное выражение. Смотрите ниже: образца на длинном тексте:

public static void main(String[] args) throws Throwable { 
    String text = "Java is a computer programming langua" 
      + "ge that is concurrent, class-based, objec" 
      + "t-oriented, and specifically designed to " 
      + "have as few implementation dependencies a" 
      + "s possible. It is intended to let applica" 
      + "tion developers \"write once, run anywher" 
      + "e\" (WORA), meaning that code that runs o" 
      + "n one platform does not need to be recomp" 
      + "iled to run on another. Java applications" 
      + " are typically compiled to bytecode (clas" 
      + "s file) that can run on any Java virtual " 
      + "machine (JVM) regardless of computer arch" 
      + "itecture. Java is, as of 2012, one of the" 
      + " most popular programming languages in us" 
      + "e, particularly for client-server web app" 
      + "lications, with a reported 9 million deve" 
      + "lopers.[10][11] Java was originally devel" 
      + "oped by James Gosling at Sun Microsystems" 
      + " (which has since merged into Oracle Corp" 
      + "oration) and released in 1995 as a core c" 
      + "omponent of Sun Microsystems' Java platfo" 
      + "rm. The language derives much of its synt" 
      + "ax from C and C++, but it has fewer low-l" 
      + "evel facilities than either of them. The " 
      + "original and reference implementation Jav" 
      + "a compilers, virtual machines, and class " 
      + "libraries were developed by Sun from 1991" 
      + " and first released in 1995. As of May 20" 
      + "07, in compliance with the specifications" 
      + " of the Java Community Process, Sun relic" 
      + "ensed most of its Java technologies under" 
      + " the GNU General Public License. Others h" 
      + "ave also developed alternative implementa" 
      + "tions of these Sun technologies, such as " 
      + "the GNU Compiler for Java (bytecode compi" 
      + "ler), GNU Classpath (standard libraries)," 
      + " and IcedTea-Web (browser plugin for appl" 
      + "ets)."; 
    System.out.println("Text:\n"+text+"\n--------------------\nWords: "+countWords(text) + "\nSentecens: " + countSentecens(text) 
      + "\nVowels: " + countVowels(text) + "\nChars: " 
      + text.toCharArray().length + "\nUpper cases: " 
      + countUpperCases(text)+"\nYour counter of words: "+yourCounter(text)); 
} 


public static int yourCounter(String myFile) { 
    if(myFile.length()==0)return 0; 
    String WORD_DELIMETERS = ".:;?!,' ]"; 
    int wordCounter= WORD_DELIMETERS.contains(myFile.charAt(0)+"")?0:1; 
    int last_Index=0; 
    for(int i=0;i<myFile.length()-1;i++){ 
     for(int j=0;j<WORD_DELIMETERS.length()-1;j++){ 
      if(myFile.charAt(i)==WORD_DELIMETERS.charAt(j)){ 
        if(myFile.charAt(i+1) !=' '){ 
         if(last_Index!=i-1){ 
          wordCounter++; 
         } 
         last_Index=i; 

        } 
       } 
      } 
    } 
    return wordCounter; 
} 

public static int countUpperCases(String text) { 
    int upper = 0; 
    char[] compare1 = text.toCharArray(); 
    char[] compare2 = text.toUpperCase().toCharArray(); 
    for (int i = 0; i < compare1.length; i++) { 
     if (compare1[i] != compare2[i]) 
      upper++; 
    } 
    return upper; 
} 

public static int countWords(String text) { 
    String pattern = "[.|:|;|?|!|,|'| ]"; 
    int counter = 0; 
    for (String word : text.split(pattern)) { 
     if (word.length() != 0) 
      counter++; 
    } 
    return counter; 
} 

public static int countSentecens(String text) { 
    String pattern = "[.|?|!]"; 
    int counter = 0; 
    for (String word : text.split(pattern)) { 
     if (word.length() != 0) 
      counter++; 
    } 
    return counter; 

} 

public static int countVowels(String text) { 
    int vowels = 0; 
    for (char c : text.toCharArray()) { 
     switch (c) { 
     case 'a': 
      vowels++; 
     case 'e': 
      vowels++; 
     case 'i': 
      vowels++; 
     case 'o': 
      vowels++; 
     case 'u': 
      vowels++; 
     } 
    } 
    return vowels; 
} 

Это возвращение:

Текст:

Java является языком программирования, который является одновременно, на основе классов, объектно-ориентированный, и специально разработанный чтобы иметь как можно меньше зависимостей реализации. Предполагается, что разработчики приложений «пишут один раз, запускаются где угодно» (WORA), что означает, что код, который работает на одной платформе, не нужно перекомпилировать для запуска на другом. Приложения Java обычно скомпилированы в байт-код (файл класса), который может работать на любой виртуальной машине Java (JVM) независимо от компьютерной архитектуры. Java с 2012 года является одним из самых популярных языков программирования, особенно для клиент-серверных веб-приложений, с сообщением о 9 миллионах разработчиков. [10] [11] Java была первоначально разработана Джеймсом Гослингом в Sun Microsystems (которая с тех пор слилась в Oracle Corporation) и выпущена в 1995 году в качестве основного компонента платформы Java Sun Microsystems. Язык извлекает большую часть своего синтаксиса из C и C++, но он имеет меньше возможностей низкого уровня, чем любой из них. Исходная и эталонная реализация Java-компиляторы, виртуальные машины и библиотеки классов были разработаны Sun с 1991 года и впервые выпущены в 1995 году. По состоянию на май 2007 года, в соответствии со спецификациями Java Community Process, Sun переиздала большинство своих технологий Java в соответствии с GNU General Public License. Другие также разработали альтернативные реализации этих технологий Sun, таких как GNU Compiler for Java (компилятор байт-кода), GNU Classpath (стандартные библиотеки) и IcedTea-Web (браузерный плагин для апплетов).


Слова: 230

Sentecens: 9

Гласные: 1597

CHARS: 1516

Верхние случаи: 1154

Ваш счетчик слов: 230

+0

Это отличная работа на Android тоже :) – barwnikk

+0

Конечно, работает на Android, почему бы и нет? – m0skit0

0

Вам нужно всего лишь одну строку:

int words = myFile.split("[" + WORD_DELIMETERS + "]+").length; 

Это использует регулярное выражение почти расколоть вход в слова, которые затем подсчитанных с помощью длину массива. Несколько последовательных разделителей рассматриваются как один разделитель, добавляя знак плюса после класса символов, поэтому «один !!!! два !!!» считается двумя словами.

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