How to get 4 last numbers from a variable?

Asked

Viewed 415 times

3

I have to get last numbers from a variable and I don’t know how to do it. I’m taking the milliseconds and I need to play in this variable lol, where I need you to return only the last 4 digits of lol not her whole.

package trabalho01;

import java.util.Calendar;

public class aleatorio {

    public int aleatoriar() {       
        Calendar lCDateTime = Calendar.getInstance();
        int lol = (int) (lCDateTime.getTimeInMillis());     
        return lol;
    }
}
  • 2

    Has the answer helped you in any way? You know how the website? Do you know that you can accept an answer that solves your problem? And you can vote for anything useful to you at website. See the[tour].

1 answer

5

You can use the module operator to get the rest of the division of 10 (our numerical base) raised to 4 (the digits you want to pick up), ie 10000.

import java.util.Calendar;

class Program {
    public static void main(String[] args) {
        System.out.println(aleatoriar());
    }
    public static int aleatoriar() {       
        Calendar lCDateTime = Calendar.getInstance();
        return (int)(lCDateTime.getTimeInMillis() % 10000);
    }
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

The intermediate variable is unnecessary (when you have difficulty giving a meaningful name to it, it is probably not useful).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.