Can someone help me with the array size? the reverse array keeps getting out of bounds and i can't figure out how to fix it. The purpose of the program is to have the user enter a sentence, the the program will find out how many palindromes are present, and what they are
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);
}
}
也许你是说
reverse[j] = reverse[j] + original.charAt(i);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.