So I am relatively new to the programming scene and I am confused as to why my code doesn't work. I am trying to make an arraylist of flowers and then use a random number generator to create a random number of certain flowers, and store them in the array. In my logic, I thought that I created a variable to store the numbers (ex randomRoses) and stored the number in the array so I could easily print out how many of each flower there is by just calling the arraylist and the position. (ex flowerArray[0] would print out 8 Roses) but sadly it does not.
public class Flower
{
private int randomRoses;
private int randomTulips;
private int randomOrchids;
public ArrayList <Integer> flowerArray;
public Flower()
{
r = new Random();
t = new Random();
o = new Random();
int randomRoses = (r.nextInt(10) + 0);
int randomTulips = (t.nextInt(10) + 0);
int randomOrchids = (o.nextInt(10) + 0);
flowerArray = new ArrayList<Integer>
}
public void add2Array ()
{
flowerArray.add(randomRoses); //flowerArray[0] is the # of roses
flowerArray.add(randomTulips); //flowerArray[1] is the # of tulips
flowerArray.add(randomOrchids); //flowerArray[2] is the # of orchids
}
public void printArray()
{
System.out.println(flowerArray[0]);
}
You can use the same random object, no need to create 3 instances of it for the random integer generation,
Random r = new Random();
for (int i = 0; i < 3; i++) {
flowerArray.add(r.nextInt(10));
}
System.out.println(flowerArray);
you can not do flowerArray[0] because you have an arrayList and not an array.
you can instead do: flowerArray.get(0) for getting the integer at pos zero
Here your array list is associated with a class object. When you initialize your array list you need to add your entries to the array list in the constructor itself. So when you say object.printArray() its actually returning you the empty array list, that's why you are getting 0 every time. Try This.
class Flower
{
private int randomRoses;
private int randomTulips;
private int randomOrchids;
public ArrayList<Integer> flowerArray;
public Flower()
{
Random r = new Random();
Random t = new Random();
Random o = new Random();
int randomRoses = (r.nextInt(10));
int randomTulips = (t.nextInt(10));
int randomOrchids = (o.nextInt(10));
System.out.println(randomRoses);
System.out.println(randomTulips);
System.out.println(randomOrchids);
flowerArray = new ArrayList<Integer>();
flowerArray.add(randomRoses); //flowerArray[0] is the # of roses
flowerArray.add(randomTulips); //flowerArray[1] is the # of tulips
flowerArray.add(randomOrchids); //flowerArray[2] is the # of orchids
}
public void printArray()
{
System.out.println(flowerArray.get(0));
}
}
public class Test {
public static void main(String[] args) {
Flower f = new Flower();
f.printArray();
}
}
And in array list you can get elements by using get(index) method.
This will give the output you expect.
public void printArray
{
System.out.println(flowerArray.get(0)+" Roses");
System.out.println(flowerArray.get(1)+" Tulips");
System.out.println(flowerArray.get(2)+" Orchids");
}
Also you missed a semi-colon after the statement defining the arraylist.
Make the correction:
flowerArray=new ArrayList<Integer>;
How did it compile without that semi-colon?
It is not working because your syntax for getting the ith flower is wrong.
You're using a java.util.ArrayList so the correct way to get an object from that ArrayList is by calling the get() method.
System.out.println(flowerArray.get(0));
Hope that helps.
Related
I am trying to randomly grab integers from another class and cannot figure out how to get those values. The first class is my initial random number generator. The second class is the class I am trying to retrieve these numbers to. I have created a grab method but cannot figure out how to retrieve these random integers from class ArrayBag. Any help would be appreciated!
import java.util.Random;
public final class ArrayBag<T> implements BagInterface<T>
{
private final T[] bag;
private int numberOfEntries;
private boolean initialized = false;
private static final int DEFAULT_CAPACITY = 6;
private static final int MAX_CAPACITY = 10000;
/** Creates an empty bag whose initial capacity is 6. */
public ArrayBag()
{
this(DEFAULT_CAPACITY);
System.out.print("Generating 6 random integers 1 - 6 in ArrayBag\n");
//Random loop to generate random numbers 1 to 6
Random rand = new Random();
for(int start=1; start <=6; start++)
{
int randInt = rand.nextInt(6);
System.out.println("Generated : " + randInt);
}
System.out.println("Finished\n");
} // end default constructor
This is my second class and method...
import java.util.Random;
public class PopulationBag
{
public PopulationBag()
{
ArrayBag ab = new ArrayBag();
LinkedBag lb = new LinkedBag();
}
/**
* Grab Method
*/
public int grab()
{
ArrayBag ab = new ArrayBag();
Random grab = new Random();
for(int start = 1; start <= 6; start++)
{
int randGrab = grab.nextInt(ab);
System.out.println("Randomly grabbed values : " + randGrab);
}
}
}
As far as I understant what you are trying to do is to build a class which genereates and holds a user-given number of random ints and second class which can access the values generated by the first class.
I've noticed a few issues with your approach. Firstly, you are generating the random numbers but never store them anyway. If the number of random ints is given by a user, you can try ArrayList approach, or use a new Java 8 approach with the method ints() of Random class (which I used in the code below). You would also need a getter method to make the access to your private variable possible.
Consider the code:
public class ArrayBag {
private int[] randomBag;
private boolean initialized = false;
private static final int DEFAULT_CAPACITY = 6;
private static final int MAX_CAPACITY = 10000;
public ArrayBag() {
Random random = new Random();
randomBag = new int[DEFAULT_CAPACITY];
// The method ints introduced in Java 8 accepts three params:
// number of ints generated, upper and lower bound between which the ints will be generated.
// toArray method passes the generated nums as an dynamically created array,
// which you can assign to a variable.
randomBag = random.ints(DEFAULT_CAPACITY, 1, DEFAULT_CAPACITY + 1).toArray();
}
// the 'getter' method
public int getRandomInt(int i) {
return randomBag[i];
}
}
/* Second class */
public class PopulationBag {
private ArrayBag ab = new ArrayBag();
private Random grab = new Random();
// Are the numbers form the ArrayBag going to be grabbed at random,
//or simply one after another?
public int[] grabInOrder(int numberOfGrabbedInts) {
// Create an array to hold ints.
int[] intBag = new int[numberOfGrabbedInts];
// Fill in data to the intBag
for (int i = 0; i < numberOfGrabbedInts; i++) {
// Call getRandomInt() method form ArrayBag class
intBag[i] = ab.getRandomInt(i);
System.out.println("Randomly grabbed values : " + intBag[i]);
}
return intBag;
}
private int[] grabAtRandom(int numberOfGrabbedInts) {
int[] intBag = new int[numberOfGrabbedInts];
for (int i = 0; i < numberOfGrabbedInts; i++) {
// This is kind of funky, basically it returns at random the ints saved in ArrayBag.
intBag[i] = ab.getRandomInt(grab.ints(1, 1, numberOfGrabbedInts).findFirst().getAsInt());
System.out.println("Randomly-randomly grabbed values : " + intBag[i]);
}
return intBag;
}
I have created two classes, one called "Bucket", and the other called "Player".
In "Bucket", I have a constructor method that creates a virtual bucket (i.e. small array) that contains three values - 1, 1, and 1. As well, I created a method to get the bucket array.
In the "Player" class, I have created a method that uses a larger array (I have called this larger array "ArrayOfBuckets"), which uses a loop to store a new bucket at each index value, up until a certain point (when i>NumberSticks). However, when I try to set
ArrayofBuckets[i] = bucketInstance.getBucket();
I get an error from Eclipse, saying that "Type mismatch: cannot convert from Bucket to int". I have spent an hour trying to solve this, to no avail. Any help would be really nice. Thanks a lot, and here is all the code that is used:
The Player Class:
import java.util.Scanner;
public class Player {
Scanner scan = new Scanner(System.in);
public String name;
private int pType;
private int[] ArrayOfBuckets;
public Player(String tempName)
{
this.name = tempName; //this. is unneccessary
}
public void ArrayOfBuckets(int NumberSticks) //this is a constructor method and creates the arrays that contains a
{
ArrayOfBuckets = new int[NumberSticks];
int i = 0;
while(i<NumberSticks)
{
Bucket bucketInstance = new Bucket();
ArrayOfBuckets[i] = bucketInstance.getBucket();//new Bucket(); //ADD THIS
i++;
}
}
and the Bucket Class:
import java.util.Random;
public class Bucket {
// private int[][] largeArray = null; //WTF DO I DO HERE
private int AIChoiceStick;
private int[] bucket;
private Random random = new Random();
private int CurrentScore[] = new int[51]; //at max, if 100 sticks are initially chosen, then each player takes at max 50 sticks,
private int h = 0; //^so why not have one more in case
public Bucket()
{
bucket = new int[3];
bucket[0] = 1;
bucket[1] = 1;
bucket[2] = 1;
public int[] getBucket()
{
return bucket;
}
You're speaking about a two-dimensional array.
private int[][] ArrayOfBuckets;
Your ArrayOfBuckets (should be just buckets according to naming conventions) is an array of arrays, so it gets two sets of square brackets.
Then the initialization:
ArrayOfBuckets = new int[NumberSticks][3];
By the way, if you want to have room for 50 elements in an array, then initialize it new int[50] so it will have indexes 0 through 49.
This question already has answers here:
Generating Unique Random Numbers in Java
(21 answers)
Closed 9 years ago.
I have this assignment:
Print 5 random integer between 1-52 with no duplicate using if/else.
Here's my code so far. It prints some numbers, but it sometimes prints duplicates.
import java.util.Random;
public class RandomCards {
public static void main(String[] args) {
Random randomCards = new Random();
int card;
for (int x = 1; x <= 5; x++) {
card = randomCards.nextInt(52) + 1;
}
if (card != randomCards) // if the value of card is not equal, proceed
{
System.out.print(card + " ");
} else {
return card; // if the value are the same get random integers again
}
}
}
public static void main(String args[]) {
Random randomNumber = new Random();
// Set stores only Unique values
Set<Integer> cards = new HashSet<Integer>();
// Iterate over to generate random numbers
while (cards.size() < 5) {
int r = randomNumber.nextInt(52) + 1;
cards.add(r);
}
for(Integer card : cards) {
System.out.println(card);
}
}
You can use this
Random randomCards = new Random();
int[] card={0,0,0,0,0};
while(card[card.length-1] == 0) {
int temp=randomCards.nextInt(52);
for(int j=0;j< card.length ; j++){
if(card[j] == 0){
card[j] = temp;
break;
}
}
}
for(int j=0;j< card.length ; j++){
System.out.println(card[j]);
}
It's not clear what you're asking, but I note from your code that you don't have any duplicate detection. You need to save each value that you generate and check for duplicates when you create a new one. I suggest creating a Set<Integer> to hold your generated values, calling add() for each new card, and checking contains() to see whether a new value has already been selected. You'd want to change your loop condition to something like cards.size() < 5 as well.
Finally, note that your use of return card is incorrect and will result in a compile-time error. return is used to end a method and send a value back to where it was called from; the main method (which is always void) has no return value, and ending the method wouldn't make sense there anyway. It looks like some code may have been copied and pasted from a version where drawCard() was its own method. Instead, just keep looping until you find 5 unique cards (such as by using the size() method I mentioned earlier).
Maybe this?
Random rand = new Random();
// ArrayList to store non-duplicate cards.
ArrayList<Integer> cards = new ArrayList<Integer>();
// Iterate over to generate random numbers
while (cards.size() < 5)
{
int r = rand.nextInt(52) + 1;
if (!cards.contains(r))
cards.add(r); // Only add if there is no such number in list
}
Hope this helps.
Hope this would be of any help.
It comprises of separate methods for computation, setting the lower and upper bound and printing the list when it has 5integers in it. Using TreeSet solves your problem of duplicates. Here it goes,
package com.project.stackoverflow;
import java.util.Random;
import java.util.Scanner;
import java.util.TreeSet;
public class RandomGenerator {
public TreeSet<Integer> compute() {
TreeSet<Integer> generatedList = new TreeSet<Integer>();
Scanner s = new Scanner(System.in);
System.out.println("Enter the lower bound for checking random numbers:");
long lowBound = s.nextLong();
System.out.println("Enter the upper bound for checking random numbers:");
long topBound = s.nextLong();
Random randomNumbers = new Random();
for (int i = 0; i < topBound; i++) {
if (generatedList.size()==5) {
break;
}
else {
generatorFunc(lowBound, topBound,randomNumbers,generatedList);
}
}
return generatedList;
}
public void generatorFunc(long lowBound,long topBound,Random randomNumbers, TreeSet <Integer> generatedList) {
long limit = topBound - lowBound;
long part = (long)(limit * randomNumbers.nextDouble());
int randomNum = (int) (part + lowBound);
generatedList.add(randomNum);
}
public void printList() {
TreeSet<Integer> testListVals = compute();
System.out.println("New" + testListVals);
}
public static void main(String[] args) {
RandomGenerator obj = new RandomGenerator();
obj.printList();
}
}
If your problem is just about the duplicates, then you can store each random number generated in an array, and for every successive call to nextint(), check if it already exists in the array of stored values, and till it does, call nextint() again for that iteration itself, else store it in the array and go to next iteration.
public class LotteryNumbers {
private ArrayList <Integer> numbers;
public LotteryNumbers() {
this.numbers = new ArrayList <Integer> ();
this.drawNumbers();
}
public ArrayList <Integer> numbers() {
return this.numbers;
}
public void drawNumbers() {
Random random = new Random ();
int counter = 0;
while (counter < 7) {
this.numbers.add(random.nextInt(39) + 1);
counter++;
}
}
This is a class used for printing 7 numbers from 1..39.
It does that job but the problem is I want the 7 random numbers to be different.
How do I check if an arrayList contains the same number since it is random?
Thanks for reading.
You could try using the contains() method from the ArrayList numbers:
public void drawNumbers()
{
Random random = new Random();
int counter = 0;
int choice;
while (counter < 7) {
choice = random.nextInt(39) + 1;
if (numbers.contains(choice)) {
continue;
}
numbers.add(choice);
counter++;
}
}
From Java Docs:
public boolean contains(Object o): Returns true if this list contains
the specified element.
So, if the ArrayList already contains the choice (randomly generated), it will continue to the next iteration (counter won't be increased) and choose another random number. If it doesn't contains the choice, it will add it to the array and increase counter.
This can also be done by this way (without using continue)
if (!numbers.contains(choice)) {
numbers.add(choice);
counter++;
}
How do I check if an ArrayList contains the same number since it is random?
Like this (example):
public void drawNumbers() {
Random random = new Random ();
int counter = 0;
while (counter < 7) {
int newNumber = random.nextInt(39) + 1;
if (! numbers.contains(newNumber)) {
this.numbers.add(newNumber);
counter++;
}
}
}
You could use contains as as the earlier responses suggest, however contains on an array list in inefficient with O(n) complexity. One of the comments by #TheLostMind suggest using a Set, the best Set implementation to use in this instance is BitSet, note it does not confirm to the java.util.Set interface specification.
public class LotteryNumbers {
private final int[] numbers = new int[7]
public LotteryNumbers() {
this.drawNumbers();
}
public int[] numbers() {
return this.numbers;
}
public void drawNumbers() {
BitSet selected = new BitSet(40);
Random random = new Random ();
int counter = 0;
while (counter < 7) {
int num = random.nextInt(39) + 1;
if(!selected.get(num)) {
selected.flip(num);
numbers[counter++] = num;
}
}
}
This implementation, tho unlikely, does not guarantee that you will always get a result.
You could also put your numbers in a list and use COllections.shuffle and get the first 7 occurences.
You do not need to check if duplicate...
ArrayList list = new ArrayList();
list.add(1);
list.add(2);
....
Collections.shuffle(list);
loop and get your numbers...
int num = Integer.intValue(list.get(i));
How do I keep tracking the value of randomNumber and then use it else where. In the code below every time I click the mouse I get random number between 0 and 10.
If I click 3 times and I get for example the values 1,6 and 7 how do I keep track of these 3 values and use them somewhere else. I want to store them in variable like, int firstClick=?;,int secondClick=?;and int thirdClick=?; how do i do that.
void mousePressed(){
int randomNumber= int(random(11));
System.out.println(randomNumber);
}
Use an ArrayList somewhere in your class:
public class MyClass {
private ArrayList<Integer> randomNumbers = new ArrayList<>();
public void mousePressed() {
int randomNumber= int(random(11));
randomNumbers.add(randomNumber);
System.out.println(randomNumber);
}
public void listNumbers() {
for (Integer number : randomNumbers) {
System.out.println(number);
}
}
}
This way, you can keep track of any number of mouse clicks and the numbers generated by them. You don't have to assign each individual number to a specific int variable.
step 1 : create an arraylist of integers
step 2 : generate random number
step 3 : store random no in arraylist
step 4 : compare this arraylist after generating new random no
step 5 : if new random no doesn't exist in arraylist , use it , store this no in arraylist
step 6 : if random no does exist in arraylist , generate another random no
//global variable
List<Integer> randomNumberArray = new ArrayList<Integer>();
then
void mousePressed()
{
for (int i = 0; i < 5; i++)
{
int temp = generateRandomNumber();
if (!randomNumberArray.contains(temp))
{
randomNumberArray.add(temp);
}
}
System.out.println(randomNumberArray);
}
public int generateRandomNumber()
{
Random randomNumber = new Random();
return randomNumber.nextInt(20);
}
or you can simply use a Set
void mousePressed()
{
Set<Integer> mySet = new HashSet<Integer>();
for(int i=0;i<5;i++)
{
int temp = generateRandomNumber();
//System.out.println(temp);
mySet.add(temp);
}
System.out.println(mySet);
}
final List<Integer> randomNumbers= new ArrayList<Integer>();
for (int i=0;i<3;i++){
randomNumbers.add(random(11));
}
// get first one
int i = randomNumbers.get(0);
This will require a variable with a scope beyond the method you are dealing with. Some options are:
// Have the random number be the return value of the method:
public int mousePressed() { return int(random(11)); }
// Have the random number be assigned to a class scoped variable:
static int someN;
public void mousePressed() { someN = int(random(11)); }
Obviously this will need to be extended to have three (or however many) values assigned/returned. The Object ArrayList<Integer> could come in handy here.