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);
    }

}
有帮助吗?

解决方案 2

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.

其他提示

Change return String.valueOf(rand);

To

 return String.valueOf(rand.nextInt());

Reason:

You are passing random Object to valueOf method, not the value you need. Call nextInt() method on it to get the desired random value.

Use

return String.valueOf(rand.nextInt());

otherwise you will get the string representation of the Random object and not of a random int that it can produce.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top