Frage

How check number on symmetrics?

public static int Symmetric(int a) {
    if(new StringBuilder(Integer.toString(a)) ==
        new StringBuilder(Integer.toString(a)).reverse())
        return  a;
    else
        return 0;
}

I try do it smth like this but always return 0.

War es hilfreich?

Lösung

You can't use == to compare Strings (or StringBuilders), you need to use equals().
Also, you need to turn the StringBuilders back to Strings before comparing:

EDIT: Also, there is really no need for the first StringBuilder:

public static int symmetric(int a) {
    if (Integer.toString(a).equals(new StringBuilder(Integer.toString(a)).reverse().toString()))
        return a;
    else
        return 0;
}

Andere Tipps

Equality is explained here in JLS.

You must use equals() on Strings: StringBuilder.toString().equals().

public static int Symmetric( int a ) {
    return
       new StringBuilder(Integer.toString(a)).toString().equals(
             StringBuilder(Integer.toString(a)).reverse().toString())
       ? a : 0;
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top