class Account {
int accountNumber;
int balance;
Account(int accountNumber, int balance) {
this.accountNumber = accountNumber;
this.balance = balance;
}
Account() {
int accountNumber = 0;
int balance = 0;
}
}
public class HW2 {
public static void main(String[] args) {
Account[] oneH = new Account[100];
accountNumberGenerator(oneH);
balanceGenerator(oneH);
for(int i = 0; i < oneH.length; i ){
System.out.println(oneH[i].accountNumber " " oneH[i].balance);
}
}
public static void accountNumberGenerator(Account[] arr){
Account one = new Account();
for(int i = 0; i < arr.length; i ){
arr[i] = one;
arr[i].accountNumber = i 1;
}
}
public static void balanceGenerator(Account[] arr){
int min = 100;
int max = 100000;
for(int i = 0; i < arr.length; i ){
Random rand = new Random();
int random_int = (int)Math.floor(Math.random()*(max-min 1) min);
arr[i].balance = random_int;
}
}
}
I'm making an object array but it's not working.
Whenever I print each values of the Account array it just shows the 100 and random number that generated last for all values.
I'm not sure what is the problem.
CodePudding user response:
public static void accountNumberGenerator(Account[] arr){
Account one = new Account();
for(int i = 0; i < arr.length; i ){
arr[i] = one;
arr[i].accountNumber = i 1;
}
}
In this method you are only creating one single instance of Account
and assigning it to every element of the array.
You need to create a brand new object each iteration of your loop.
public static void accountNumberGenerator(Account[] arr){
for(int i = 0; i < arr.length; i ){
Account one = new Account();
arr[i] = one;
arr[i].accountNumber = i 1;
}
}
CodePudding user response:
Here's a simple way to create 100 accounts.
public class Main {
public static void main(String[] args) {
java.util.Random r = new java.util.Random();
Account[] oneH = new Account[100];
for(int i=0; i<oneH.length; i )
oneH[i] = new Account(i, r.nextInt(99900) 100);
for(int i = 0; i < oneH.length; i )
System.out.printf("=}\n", oneH[i].accountNumber, oneH[i].balance);
}
}