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.

asked Oct 7, 2015 at 18:03
\$\endgroup\$
0

1 Answer 1

3
\$\begingroup\$

Use Math.abs()

 public static int lastDigit(int x) {
 return Math.abs(x % 10);
 }
TheCoffeeCup
9,5164 gold badges38 silver badges96 bronze badges
answered Oct 7, 2015 at 18:26
\$\endgroup\$
3
  • \$\begingroup\$ Well I feel somewhat stupid. Thanks though \$\endgroup\$ Commented Oct 7, 2015 at 20:05
  • \$\begingroup\$ Figured courses should be teaching if-else before static methods invocation... oh wells. \$\endgroup\$ Commented Oct 8, 2015 at 0:56
  • \$\begingroup\$ I make all methods static just to avoid problems. \$\endgroup\$ Commented Oct 8, 2015 at 17:32

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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