Thread: help student
View Single Post
  #13 (permalink)  
Old 01-30-2008, 01:41 AM
gibsonrocker800's Avatar
gibsonrocker800 gibsonrocker800 is offline
Senior Member
 
Join Date: Nov 2007
Location: New York
Posts: 143
gibsonrocker800 is on a distinguished road
Send a message via AIM to gibsonrocker800
Quote:
Originally Posted by jvasilj1 View Post

this is my code
-------------------------------------
// Check to see if an input string is a palindrome
// orig is the original string,
// processed is the string after removing all characters
// that are not letters and converting to upper case.

import java.util.Scanner;

public class PalindromeCheck
{
private static void main(String argv)
{
String orig, processed, letter;
int left, right;
Scanner con = new Scanner(System.in);

System.out.println("Enter a string:");
orig = con.next;
for(int i = 0; i < orig.length( ); i++)
{
letter = orig.charAt(i);
if (Character.isLetter(letter))
processed += Character.toUpperCase( );
}

if (processed.length( ) < 0);
{
left = 0;
right = processed.length( );
while (left < right)
{
if (processed.charAt(left) != processed.charAt(right))
System.out.println("String is not a palindrome.");
else
System.out.println("String is a palindrome.");

left++;
right--;
}
System.out.println("String is a palindrome.");
}

}
}

First of all. the main method is public static void main(String[] args)

private static void does not exist. I saw a thread a while ago asking why the main method is public. I actually found the answer in a book. It is because the method needs to be accessed at runtime.

Second
letter should be a char, not a String.

Third
Code:
processed += Character.toUpperCase( );
the toUpperCase method needs a char as its parameters. So, we will pass letter to it.

Last
Code:
if (processed.charAt(left) != processed.charAt(right))
It should be right - 1, since we are dealing with indexes.

Here is the updated code:


Code:
import java.util.Scanner; public class PalindromeCheck { public static void main(String args[]) { String orig, processed; processed = ""; char letter; int left, right; Scanner con = new Scanner(System.in); System.out.println("Enter a string:"); orig = con.next(); // for(int i = 0; i < orig.length( ); i++) { letter = orig.charAt(i); if (Character.isLetter(letter)) processed += Character.toUpperCase(letter); } if (processed.length( ) < 0); { left = 0; right = processed.length( ); while (left < right) { if (processed.charAt(left) != processed.charAt(right-1)) System.out.println("String is not a palindrome."); else System.out.println("String is a palindrome."); left++; right--; } System.out.println("String is a palindrome."); } } }
__________________
//Haha javac, can't see me now, can ya?
Reply With Quote