Daniel Vassallo
Daniel Vassallo

Reputation: 21

In a class called Digit, write a method called lastDigit that returns the last digit of an integer number

This is a homework question that I am stumped on. My professor suggests looking up the Math.abs() method.

I need to utilize a Scanner object in the main method to query for input from the user and then use the Scanner input as parameters to the specified methods. In a class called Digit, write a method called lastDigit that returns the last digit of an integer number. For example, lastDigit(3572) should return 2.

Here is what I currently have:

import java.util.Scanner;

public class Digit {

    public static void main(String[] args) {
        Scanner scanIn = new Scanner(System.in);

        System.out.print("Please enter a number: ");
        int = scanIn.nextInt();


    }
    public int lastDigit(int number){
        int last =number%10;
        return last;

    }

}

Upvotes: 0

Views: 1135

Answers (1)

kviiri
kviiri

Reputation: 3302

Java preserves sign when handling the modulo. 105 % 10 == 5 while -105 % 5 == -5. You need to get rid of the minus sign for negative numbers, and Math.abs allows you to do precisely that: return Math.abs(last); should work.

For a slightly more verbose solution, you could check if the solution would be negative, and multiply by -1 if that is the case.

Upvotes: 1

Related Questions