Hi there.
For a homework assignment I'm supposed to write an applet that tells whether or not a String input by the user is a palindrome. I think I have the logic worked out (and if I don't, I can fix that part myself), but this is my first GUI. The following compiles, but I keep getting an OutOfBounds exception (it says on line 38, which is where the variable indexTwo is defined) whenever the button is clicked. I'm not sure why; if it's just a little error or I need to approach it differently.
It's a little bit messy, I just want to make it work. Also, I originally had two classes and used a array, but the prof said the assignment should be one class per question and no arrays were needed (which I think is silly for a couple of the questions, but whatever).
Code:// leading comments etc import javax.swing.*; import java.awt.*; import java.awt.event.*; public class PalindromeTest extends JApplet implements ActionListener { private JTextField inputString; private JButton theButton; //oh, and should I move this to the init() method? private JLabel truthLabel; public void init() { truthLabel = new JLabel("Input your text and click the button."); theButton = new JButton("Is it a palindrome?"); inputString = new JTextField(20); theButton.addActionListener(this); Container contentPane = getContentPane(); contentPane.setLayout(new FlowLayout()); contentPane.add(inputString); contentPane.add(theButton); contentPane.add(truthLabel); } public void actionPerformed(ActionEvent e) { String strIn = inputString.getText(); String str = strIn.toUpperCase(); //possibly redundant? boolean isPalindrome = true; int indexOne = 0; //beginning of the string (index marker 1) int indexTwo = str.length(); //ending of the string (index marker 2) while (indexOne < indexTwo){ char charOne = str.charAt(indexOne); char charTwo = str.charAt(indexTwo); if (charOne != charTwo){ //exceptional case isPalindrome = false; break; } else { indexOne += 1; //move the first marker to the right indexTwo -= 1; //move the second marker to the left } } //end of the while loop if (isPalindrome) truthLabel.setText("That is a palindrome."); else truthLabel.setText("That is not a palindrome."); } }



Reply With Quote


Bookmarks