javarandomobject-to-string

Field with random int value


I'm writing a program that simulates simple bank account activities and I was wondering how to do it so that if I create a new Account without any parameters, it receives random 7digit identification number that is shown as String. The way I do, I only receive java.util.Random@2a0364ef in output. Looking forward to any help and additional comments on this question as it is the first one I've posted on this website.

    import java.util.Random;

    class Account {

    String id;
    double stan;
    int num;
    static int counter;

    public Account() {
        **id = randomId().toString();**
        stan = 0;
        num = ++counter;

    }

    public Account(String id) {
        this.id = id;
        stan = 0;
        num = ++counter;

    }

    public Account(String id, double mon) {
        stan = 0;
        this.id = id;
        this.stan = mon;
        num = ++counter;

    }

    **static String randomId() {
        Random rand = new Random(7);
        return String.valueOf(rand);**
    }

    String getId() {
        return id;
    }

    double getStan() {
        return stan;
    }

    int getNum() {
        return num;
    }

    @Override
    public String toString() {
        return "Account's id " + getId() + " and balance " + getStan();
    }
}

public class Exc7 {

    public static void main(String[] args) {
        Account account = new Account("0000001"),
                acount0 = new Account("0000002", 1000),
                acount1 = new Account();




        System.out.println(account + "\n" + account0 + "\n" + account1);
    }

}

Solution

  • Use this code:

    Random rand = new Random(7);
    return String.valueOf(Math.abs(rand.nextInt()));
    

    Right now you are representing the Random instance.

    Instead printing the String representation of the mathematical absolute of the next int of your random will do the trick.

    The Math.abs part is important, otherwise you might have negative numbers.