Why do I get 0 in the outputs?
I am trying to generate 100 random numbers between 1 and 1000. Then, I need to find their average and which of them is their maximum. I get a wrong output. How do I fix this?
Thank you very much.
Code :
import java.util.Random;
public class DataSet
{
private Random randomGenerator;
private int randomInt;
private int total;
private double average;
private int highestValue = 1;
public void Dataset()
{
total = 0;
for (int i = 1; i <= 100; i++)
{
randomInt = randomGenerator.nextInt(1000);
total = total + randomInt;
if(highestValue < randomInt)
{
highestValue = randomInt;
}
}
}
public double getAverage()
{
average = total/100;
return average;
}
public int getMaximim()
{
return highestValue;
}
public int getRandomInt()
{
return randomInt;
}
}
Code :
public class DataSetTester
{
public static void main(String[] args)
{
DataSet jean = new DataSet();
System.out.println("The average of the generated numbers is: " + jean.getAverage());
System.out.println("The highest number of the generated random numbers is: " + jean.getMaximim());
}
}
Re: Why do I get 0 in the outputs?
Break the problem down. Try doing a smaller range of random numbers, or less of them, or better yet even using some fixed numbers to which you know the answer. Add some println's debug statements in there to make sure each portion of code is producing what you expect.
Re: Why do I get 0 in the outputs?
Re: Why do I get 0 in the outputs?
Quote:
Originally Posted by
jean28
...I am trying to generate 100 random numbers...I get a wrong output....
What method is responsible for generating the numbers?
Try putting some print statements in that function that go something like:
Code java:
.
.
.
System.out.println("Generating 100 random numbers");
for (int i = 1; i <= 100; i++)
{
randomInt = randomGenerator.nextInt(1000);
System.out.println("randomInt = " + randomInt);
.
.
.
If you don't understand the output from these statements (or lack thereof), put a print statement in your main() method where you are calling that function.
Cheers!
Z