How to calculate item price from random quantity of items sold?

Asked

Viewed 64 times

-2

I’m solving a problem, and one of the parts of it is calculating the price of an item based on the random amount of this same item sold. For example: 4 items were sold, so the method should calculate the price of 4 items sold. This number 4 was generated randomly.

I created a class, which has as variables the items to be sold, created a method for each item, to generate a random value of each item, and other methods, to generate the price of the items based on the amount of items sold (randomly generated). The problem is that the amount of items generated is not matching the price of the items sold.

Here is the method to generate a random amount of burgers, for example:

public class Mês {
private int hamb;

public double vendaHamb (){
    Random rand = new Random();
    hamb = rand.nextInt(5)+1;
    return hamb;
}

public double precoHamb (){
    double preco= vendaHamb()*78.00;

    return preco;
}
}

I’ve looked into a lot of similar cases, and I haven’t. When I create a class object, and I try to calculate the number of burgers sold, and their price, the value of the burgers sold is randomly generated, but their price too, the price does not match the value of the items sold, as if it did not use the number that was actually generated. I’d appreciate it if you could help me.

  • Try changing the return type of the method to int.

  • 1

    I think what happens is that it generates a new number Randon to each call, that is, if you call the salesHamb it returns a number, and if soon in sequence Voce call the precoHamb it will call the salesHamb and will generate a new randomic number...

  • I assumed the same thing. Therefore, I would like to know if anyone has any idea how to use the first randomly generated value, but fixed in the second method. I’ve searched a lot about it, but I haven’t found anything, so maybe it’s not even possible, but since I’m still learning, I’m not sure.

1 answer

1


public double precoHamb (){
   double preco= vendaHamb()*78.00;

   return preco;
}

Try changing this snippet of code to:

public double precoHamb (){
   double preco= hamb * 78.00;

   return preco;
}

Otherwise each time you calculate the value of the burger will generate a new random number.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.