if statement - Java Beginner Program Help (if, else issue) -
i'm practicing making own string reversal tool. top learning process of used method in simple application. but..
when run code in eclipse, if word = racecar , reversed becomes = racecar (word reversed). else displayed.. telling me word , reverse never equal.. but..ion case are? right? please give me advice, quite bummer. thank you.
import java.util.scanner; public class main { static scanner sc = new scanner(system.in); public static void main(string[] args){ system.out.println("please enter word, i'll show reversed "); system.out.println("and tell if read same forward , backward(a palindrome)!: "); string word = sc.nextline(); string reverse = reverse(word); if (reverse == word){ system.out.println("your word: " + word + " backwards " + reverse + "."); system.out.println("your word read same forward , backward!"); system.out.println("its palindrome!"); } else { system.out.println("your word: " + word + " backwards " + reverse + "."); system.out.println("your word not read same forward , backward!"); system.out.println("its not palindrome!"); } } public static string reverse(string source){ if (source == null || source.isempty()){ return source; } string reverse = ""; for(int = source.length() -1; >= 0; i--){ reverse = reverse + source.charat(i); } return reverse; } }
always use string#equals compare strings. ==
compare if references equal doesn't work comparing equal strings due how stored.
if (reverse.equals(word))
Comments
Post a Comment