java - Palindrome ... i think the error is in my if statement because it keeps putting the output as 'it's not' -
most error in if statement, want if word not palindrome display it's not.
package palindrome; import java.util.scanner; /** * * @author */ public class palindrome { /** * @param args * command line arguments */ public static void main(string[] args) { integer length; integer lasttofirst = 0; integer firsttolast = 0; boolean result = true; string palindrome = (""); scanner inputkey = new scanner(system.in); system.out.print("enter word: "); palindrome = inputkey.nextline(); char[] newword = palindrome.tochararray(); length = palindrome.length(); system.out.println("the length is: " + length); if (newword[firsttolast] == newword[lasttofirst]) { firsttolast = lasttofirst + 1; } if (firsttolast == lasttofirst) { lasttofirst = firsttolast + 1; // result = true; } if (newword[lasttofirst] == newword[firsttolast]) { firsttolast = lasttofirst + 1; system.out.println("it palindrome "); } else { system.out.println(" it's not"); } } }
you start with:
integer lasttofirst = 0; integer firsttolast = 0;
and check:
if (newword[firsttolast] == newword[lasttofirst])
which true; set:
firsttolast = lasttofirst + 1;
and check:
if (firsttolast == lasttofirst)
which false (since 1 != 0
) , check if:
if (newword[lasttofirst] == newword[firsttolast])
which equivalent of:
if (newword[0] == newword[1])
so, true if first 2 characters same.
the conclusion is: aren't checking if palindrome @ all, doing checking first 2 characters.
i like:
import java.util.scanner; public class palindrome { public static boolean ispalindrome( final string string ){ if ( string == null ) return false; ( int = 0, j = string.length() - 1; < j; i++, j-- ){ if ( string.charat(i) != string.charat(j) ) return false; } return true; } public static void main( final string[] args ){ string input; final scanner scanner = new scanner( system.in ); while ( (input = scanner.nextline()).length() > 0 ){ system.out.println( ispalindrome( input ) ); } } }
Comments
Post a Comment