0
\$\begingroup\$
public static int lastDigit(int a) {
    a = a % 10;
    if (a <= 0){
    a *= -1;
    }
    return a;
}

This is my solution. The course hasn't taught if else yet, so I'm wondering if there is a way to do it without the if else.

public static int lastDigit(int a) {
a = a % 10;
return a;
}

The problem with this is that it will not print the last digit of a negative number as a positive.

\$\endgroup\$
0

1 Answer 1

3
\$\begingroup\$

Use Math.abs()

 public static int lastDigit(int x) {
      return Math.abs(x % 10);
 }
\$\endgroup\$
3
  • \$\begingroup\$ Well I feel somewhat stupid. Thanks though \$\endgroup\$
    – user85459
    Commented Oct 7, 2015 at 20:05
  • \$\begingroup\$ Figured courses should be teaching if-else before static methods invocation... oh wells. \$\endgroup\$
    – h.j.k.
    Commented Oct 8, 2015 at 0:56
  • \$\begingroup\$ I make all methods static just to avoid problems. \$\endgroup\$
    – user85459
    Commented Oct 8, 2015 at 17:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.