Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    Regular Coder
    Join Date
    Oct 2011
    Posts
    106
    Thanks
    12
    Thanked 0 Times in 0 Posts

    Always returns false:

    I have a method to test if a number is palendromic (the function is public boolean isPalen(int n))

    It always returns false. Even if I change main to pass in a palendromic number directly.
    Why? Can someone give me some tips?
    Code:
    public class Main {
    	public static void main(String args[]){
    		System.out.println("Starting....");
    		Thread t1 = new Thread(){
    			public void run(){
    				new Main().loop(10,99);
    			}
    		};
    		t1.start();
    		System.out.println("Done!");
    	}
    	public void loop(int l, int h){
    		for(int ih = l; ih <= h; ih++){
    			for(int il = 10; il < 100; il++){
    				if(isPalen(ih * il))
    					System.out.println("\t" + ih * il);
    			}
    		}
    	}
    	public boolean isPalen(int n){
    		String s1 = Integer.toString(n);
    		String s2 = reverse(s1);
    		
    		return (s1 == s2);
    		
    	}
    	public String reverse(String s) {
    	    return new StringBuffer(s).reverse().toString();
    	}
    }

  • #2
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,979
    Thanks
    4
    Thanked 2,659 Times in 2,628 Posts
    return (s1 == s2); compares the memory space of two objects. Strings cannot be compared this way, you must use s1.equals(s2).


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •