Yes, I'll admit, I am a newbie in Java. However, now my brains got fried on this thing - picking random objects from wherever (example of an Array).
Before detailing, my main question is: how do you use Random generator on objects (arrays, arraylists etc.)? (Not Int, Not String) I.e. how do you converts objects so that the Random generator can pick them?
Assume following:
Class Bankaccount
Objects Bankaccounts (with attributes like balance, id etc.) - these are stored in an array.
How can I pick, say 3 random objects (bankaccounts) from an array of say 10 bankaccounts?
Code example:
import java.util.*;
import java.util.Random;
class Bankaccount{
private int balance;
public void setBalance(int a){
balance = a;
}
public int getBalance(){
return balance;
}
}
//Alright, I am thinking of creating a new class which has a method that calls on the array of type Bankaccount and stores it
//in whatever area, for example another array or arraylist.
class pickRand{
public static Bankaccount [] get(Bankaccount[]array){
Random rand = new Random();
int rnd = rand.nextInt(array.length);
//Objects to int - how to? Any hints?
//Can a solution be to attack the balance variable of objects?
//The other part of adding those objects is ok, and also how many to pick.
}
}
public class Account{
public static void main(String []args){
Bankaccount b1 = new Bankaccount();
Bankaccount b2 = new Bankaccount();
Bankaccount b3 = new Bankaccount();
Bankaccount b4 = new Bankaccount();
Bankaccount b5 = new Bankaccount();
Bankaccount b6 = new Bankaccount();
Bankaccount b7 = new Bankaccount();
Bankaccount b8 = new Bankaccount();
Bankaccount b9 = new Bankaccount();
Bankaccount b10 = new Bankaccount();
b1.setBalance(10000);
b2.setBalance(30000);
b3.setBalance(13000);
b4.setBalance(36000);
b5.setBalance(19000);
b6.setBalance(28000);
b7.setBalance(30000);
b8.setBalance(30000);
b9.setBalance(15000);
b10.setBalance(30000); //Yes, very thorough, but look up! :)/>
Bankaccount [] bac = new Bankaccount [10];
bac[0] = b1;
bac[1] = b2;
bac[2] = b3;
bac[3] = b4;
bac[4] = b5;
bac[5] = b6;
bac[6] = b7;
bac[7] = b8;
bac[8] = b9;
bac[9] = b10;
//The final output looks something like this...
Bankaccount[]bac2 = pickRand.get(bac);
System.out.println(bac2);//and so on.
}
}
Any hints will be greatly appreciated! However, please keep me in the Random generator area!

New Topic/Question
Reply
MultiQuote






|