View Full Version : Java newbie, GUI question

11-20-2008, 04:13 PM
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).

// 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);
Container contentPane = getContentPane();
contentPane.setLayout(new FlowLayout());

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;

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.");
truthLabel.setText("That is not a palindrome.");


01-28-2009, 08:14 PM
You need exactly to add two more characters to your source to fix the problem.
HINT: Indexing in Java is 0 based. That is starts at 0. :)

There isn't much more I can say without giving it away.

03-18-2009, 10:07 PM
I love silly mistakes!

I assume that you have already figured it out, but if you haven't then ill give another hint just because I had to do a palindrome checker... An array of size 5 has the values 0 through 4. If that didn't blatantly give it away then you don't belong in computer science.

Sorry if those of you out there don't like that I made it easy, but I doubt that it isn't just a stupid mistake that the poster already knows the answer to but didn't notice.