Search code examples
javaarraysloopsvariable-length-array

Returning the last digit of every number in an array


My problem is that I'm trying to return the last digit of every element in an int array but the function below rather returns the last element of the array. How would I go about doing this.

Array: {10, 12, 41, 23, 71}

Expected output: 0, 2, 1, 3, 1

public class TestForEachLoop
{
    private int[] iLoop = new int[5];
    
    public int getLastDigit(){

        int[] iLoop = new int[]{10, 12, 41, 23, 71};
        int lastnumber = iLoop[iLoop.length - 1];
        return lastnumber;
    }    
}

Solution

  • You can use modulo operator to get the last digit of a number and then use the abs method in the Math class to get the positive value.

    public class Main {
        
        public static int getLastDigit(int n){
            int lastDigit = Math.abs(n % 10);
            return lastDigit;
        }
        
        public static void main(String[] args){
            int[] iLoop = new int[]{10, 12, 41, 23, 71};
            for(int i = 0; i < iLoop.length; i++){
                System.out.print(getLastDigit(iLoop[i]) + " ");
            }
        }
    }