2016-12-04 1 views
-1

Я здесь новый. Я был бы признателен за некоторую помощь, я пытаюсь написать программу, чтобы найти палиндромы в предложении, это то, что у меня есть до сих пор. Однако всякий раз, когда я его выполняю, количество палиндрома приходит к нулю, а System.out.println в for и ifs не происходит, я не могу понять, что не так. мы должны использовать для цикла, а не во время.Как проверить количество палиндромов в предложении?

import java.util.Scanner; 

class palcheck { 
    public void main() { 
     Scanner sc = new Scanner(System.in); 
     System.out.println("Enter the sentence please...");// input sentece 
     String s = sc.next();// the sentence 

     String wordback = ""; //reverse of a word of the sentence 
     int count = 0; // palindrome count 
     String word = "";// for a word of the sentence 
     int a; // counter 
     String s2 = null; //sentence but with removed full stop 

     if (s.charAt(s.length() - 1) == '.')// checking if ends with fullstop 

     { 
      s2 = s.substring(0, (s.length() - 1)); 
     }// sentence without fullstop 
     System.out.println(s2); 
     String s3 = " " + s2 + " "; 
     System.out.println(s3);// added a space; 
     for (int c = 0; c < s3.length(); c++) { 
      char isspace = s3.charAt(c); 
      if (isspace == ' ')// checking 
      { 
       char x = ' ';// initilaizing 
       for (a = s3.indexOf(isspace); x != ' '; a++) { 
        x = s3.charAt(a); //collecting letters for word 
        word = word + x; // forming word 
        System.out.println("word is " + word);// the formed word 
       } 
       int l2 = word.length(); 
       for (int i = l2 - 1; i >= 0; i--) { 
        wordback = wordback + word.charAt(i);// forming reverse word 
        System.out.println("reverse word is " + wordback); 
        if (word.equalsIgnoreCase(wordback)) { 
         count = count + 1; 
        }// increasing palindrome count 
        word = null;// resetting value 
        wordback = null;//resetting value 
       } 
      } 
     } 
     System.out.println("the no of palindromes is " + count); 
    } 
} 

Edit: Я попытался изменить имена переменных:

import java.util.Scanner; 

class palcheck { 
    public void main() { 
     Scanner sc = new Scanner(System.in); 
     System.out.println("Enter the sentence please...");// input sentece 
     String sentence = sc.next();// the sentence 

     String wordreverse = ""; //reverse of a word of the sentence 
     int count = 0; // palindrome count 
     String word = "";// for a word of the sentence 
     int a; // counter 
     String sentencewithoutfullstop = null; //sentence but with removed full stop 

     if (sentence.charAt(sentence.length() - 1) == '.')// checking if ends with fullstop 

     { 
      sentencewithoutfullstop = sentence.substring(0, (sentence.length() - 1)); 
     }// sentence without fullstop 
     System.out.println(sentencewithoutfullstop); 
     String sentencewithspace = " " + sentencewithoutfullstop + " "; 
     System.out.println(sentencewithspace);// added a space; 
     for (int c = 0; c < sentencewithspace.length(); c++) { 
      char isspace = sentencewithspace.charAt(c); 
      if (isspace == ' ')// checking 
      { 
       char letter = ' ';// initilaizing 
       for (a = sentencewithspace.indexOf(isspace); letter != ' '; a++) { 
        letter = sentencewithspace.charAt(a); //collecting letters for word 
        word = word + letter; // forming word 
        System.out.println("word is " + word);// the formed word 
       } 
       int length2 = word.length(); 
       for (int i = length2 - 1; i >= 0; i--) { 
        wordreverse = wordreverse + word.charAt(i);// forming reverse word 
        System.out.println("reverse word is " + wordreverse); 
        if (word.equalsIgnoreCase(wordreverse)) { 
         count = count + 1; 
        }// increasing palindrome count 
        word = null;// resetting value 
        wordreverse = null;//resetting value 
       } 
      } 
     } 
     System.out.println("the no of palindromes is " + count); 
    } 
} 

EDIT: Я переделано программу, но ее не получают казнены. Я использую bluej, и всякий раз, когда я выбираю void (main), виртуальная машина Java продолжает работать, и я должен ее окончательно завершить.

Есть ли проблемы в программе?

import java.util.Scanner; 

class cal { 
    public static void main(String args[]) { 
     Scanner sc = new Scanner(System.in); 
     String input = sc.next(); 
     String word = null; 
     String reverse = null; 
     int count = 0; 
     if (input.endsWith(".")) { 
      String Sent2 = input.substring(0, (input.length() - 1)); 
      String sent3 = " " + Sent2 + " "; 
      int l = sent3.length(); 
      for (int i = 0; i < l; i++) { 
       if (sent3.charAt(i) == ' ') { 
        while (sent3.charAt(i + 1) != ' ') { 
         char h = sent3.charAt(i + 1); 
         word = word + h; 
         int l2 = word.length(); 
         for (int j = l2 - 1; j >= 0; j--) { 
          char hg = word.charAt(j); 
          reverse = reverse + hg; 
          if (word.equalsIgnoreCase(reverse)) { 
           System.out.println("palindrome :" + word); 
           count++; 
          } 
         } 
        } 
       } 
      } 
     } else { 
      String sent3 = " " + input + " "; 
      int l = sent3.length(); 
      for (int i = 0; i < l; i++) { 
       if (sent3.charAt(i) == ' ') { 
        while (sent3.charAt(i + 1) != ' ') { 
         char h = sent3.charAt(i + 1); 
         word = word + h; 
         int l2 = word.length(); 
         for (int j = l2 - 1; j >= 0; j--) { 
          char hg = word.charAt(j); 
          reverse = reverse + hg; 
          if (word.equalsIgnoreCase(reverse)) { 
           System.out.println("palindrome :" + word); 
           count++; 
          } 
         } 
        } 
       } 
      } 
     } 
    } 
} 
+1

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

+2

И подсказка: посмотрите, как правильно форматировать ваш код. Это материал в 10 раз труднее читать, чем следовало бы. И: используйте лучшие имена для ваших переменных. s1, s2, s3 ... говорит ** ничего ** о содержании этих вещей. Наконец: вы можете использовать String.split (""), чтобы разделить ваше предложение на части; вам не нужно вручную сканировать пробелы! – GhostCat

+0

@GhostCat большое спасибо! Я попытался лучше назвать переменные и загрузит их. Однако мы еще не выполнили функцию String.split в школе, и я не уверен, одобрит ли наш учитель, но я попробую еще раз. Благодаря! –

ответ

0

Этот код предполагает, что вы имеете inputString и находит палиндромов внутри него.

String word = ""; 
String inverse = ""; 
for (int index = 0; index < input.length(); index++) { 
    if (input.charAt(index) == " ") { 
     if ((word.length() > 0) && (word.equals(inverse))) { 
      System.out.println("Palindrome: " + word); 
     } 
     word = ""; 
     inverse = ""; 
    } else { 
     char current = input.charAt(index); 
     word += current; 
     inverse = current + inverse; 
    } 
} 
if ((word.length() > 0) && (word.equals(inverse))) { 
    System.out.println("Palindrome: " + word); 
} 
+0

Спасибо вам большое! Однако всякий раз, когда я пытаюсь выполнить его таким образом, только первое слово распознается как палиндром, если это палиндром. есть ли способ исправить это? –

+0

@viktornikiforov, можете ли вы дать мне пример ввода, где произошла ошибка, о которой вы говорите, и можете ли вы описать полученный результат? –

+0

Ааа хорошо, я понял, где я ошибся!^_ ^; Я брал sc.next() вместо sc.nextLine(), и поэтому он не читал полное предложение .. Spasibo! –

0

пожалуйста избежать Systax Ошибка в коде:

В Java, основная функция должна иметь следующий

public static void main(String args[]) 
{ 

и цикл у не указано условие не удовлетворяется .because перед циклом у инициализируется как,

char letter = ' ' ;// initilaizing 
for(a = sentencewithspace.indexOf(isspace); letter !=' ' ;a++) 

один раз, условие цикла удовлетворительное, тогда только внутри блока, чтобы быть казнены.

Пожалуйста, не используйте indexOf() в цикле. Причина - java throw StringIndexOutOfBoundsException, когда индекс String выходит за пределы диапазона.

см ссылку: http://www.vinaysingh.info/palindromic-words/

how to count the number of words of the same(PALINDROME) in java

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

  • Нет связанных вопросов^_^