我不断出错

时间:2013-03-01 00:34:08

标签: java arrays

有人可以帮我解决数组大小问题吗?反向数组不断超出范围,我无法弄清楚如何解决它。该程序的目的是让用户输入一个句子,该程序将找出存在多少回文,以及它们是什么

package palindrome;

import java.util.*;
 import javax.swing.*;

class Palindrome2
{
   public static void main(String args[])
   {
  //String[] reverse; //Reverse word
  String[] words;
  int count = 0;
  String palindromes[];

  //User Input
  String original = JOptionPane.showInputDialog("Words that are the same "
          + "forwards and backwards are called palindromes.\n"
          + "This program determines if a word is a palindrome.\n\n"
          + "Enter a word: ");

  //Length of the Input
  int length = original.length();


  //Spliting the original into an Array

  words = original.split("\\s");



  //Reversing the User's Input
  String[] reverse = new String[words.length];


  for(int j = 0; j < words.length; j++){

      int wordLength = words[j].length();

      for ( int i = wordLength - 1 ; i >= 0 ; i-- ) {
       reverse[i] = reverse[i] + original.charAt(i);
   }
  }

  //Determining if it is a Palindrome and Output 


  for (int l = 0; l < words.length; l++){

      if (original.equalsIgnoreCase(reverse[l])) {

       count = count + 1;

       palindromes = new String[count];
       palindromes[l] = reverse[l];


   }
  else {

  }
   }

JOptionPane.showMessageDialog(null, "There are " + count + " Palindromes"
        + " in this sentence");

JOptionPane.showMessageDialog(null, "The palindromes are:\n"+ palindromes);

}

}

1 个答案:

答案 0 :(得分:0)

也许你的意思是

reverse[j] = reverse[j] + original.charAt(i);