Search code examples
javamethodsbluejuser-defined

How to compare last digit of number w/ last digit of another number?


public static boolean retsim(int x, int y)
{
    String xx = x + "";
    String yy = y + "";
    boolean returnValue = false;
    if(xx.substring(xx.length() - 1) == yy.substring(yy.length() - 1))
    {
        returnValue = true;
    }
    return returnValue;
}

So when I compile and run this there are no errors. Yet it prints out 2 false statements, when there should be only one true or false statement. Like for example:

Enter in two sets of numbers with either,
The same or different end digit
7
7
// ^^ The two sevens are the inputs
false
false
// ^^ The two false statements that should only be printing out one

When the last digit is the same as the other last digit it should return true, and when those two digits are not the same the program should return false. Please help?!

public static boolean retsim(int x, int y)
{
    String xx = x + "";
    String yy = y + "";
    boolean returnValue = false;
    if(xx.substring(xx.length() - 1).equals(yy.substring(yy.length() - 1)))
    {
        returnValue = true;
    }
    return returnValue;
}

Now it returns:

Enter in two sets of numbers with either,
The same or different end digit
7
7
// ^^ The two sevens are the inputs
true
false
// ^^ The two false statements that should only be printing out one

Anyone have any ideas on how to get rid of that last false?

The code I use to call the class is:

public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.println("Enter in two sets of numbers with either,\nThe same or different end digit");
int x2 = console.nextInt();
int y = console.nextInt();
System.out.println(retsim(x2,y));
}

Solution

  • The very first comment from zapl already gives a great hint.

    public static boolean retsim(int x, int y)
    {
        return Math.abs(x)%10 == Math.abs(y)%10;
    }