I'm trying to make a Palindrome program and this loop is giving me trouble:

for (int i= 0; i < 79; i++) 
{   
character[i] = scan.next(); 
if (character[i] == ".") 
{break; 
}   

} 

The user enters a word, and when they are done, they enter a period, which is supposed to break them out of the loop. But when I run the program and enter a period, nothing happens. It just allows me to enter letters until the array is full. Why is the program skipping over the if-statement?

Here is the full program (And yes, I'm sure there are plenty of other mistakes, but I'll try to fix them on my own later. Forgive me, I'm new to Java):

import java.util.Scanner; 

public class Palindrome { 


public static void main(String[] args) { 

System.out.println("Please enter a word or phrase. Enter a '.' when you are done."); 
Scanner scan = new Scanner (System.in); 
String[] character = new String[79]; 


for (int i= 0; i < 79; i++) 
{ 

character[i] = scan.next(); 
if (character[i] == ".") 
{break; 
}   

} 

if (isPalindrome(character)==true) 
{System.out.println("It is a palindrome."); 
} 
if (isPalindrome(character) != true) 
{System.out.println("It is not a palindrome."); 
} 
} 



public static Boolean isPalindrome (String[] chars){ 

String[] reverse = new String[79]; 
for (int i=reverse.length-1;i>=0; i--) 
{ 


if(reverse[i] == chars[i]) 
{return true; 
} 
else 
return false; 


} 



} 
}

Recommended Answers

All 3 Replies

Any ideas? I've been working on this for hours and I still don't know what the problem is.

a lot of ideas.
for starters, don't hardcode that 79. use the length of the word.
also don't use arrays of Strings. use a String and the charAt method, or myString.toCharArray();

you are having problems with this:

for (int i= 0; i < 79; i++) 
{ 
character[i] = scan.next(); 
if (character[i] == ".") 
{break; 
}   

why do you even have that? just read it using nextLine(); and use the split method of the String class with "." as separator.

why that loop to check your string? Just use the reverse() method from StringBuilder and check whether the result is equal to the original.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.