Generate a three-digit random number 100 times. Display the output for each of t
ID: 3558536 • Letter: G
Question
Generate a three-digit random number 100 times. Display the output for each of the generated numbers and the sum of all 100 numbers.
This is my code just need help with sum portion. I have tried several things but have not been able to add all the random numbers.
import java.util.Random;
public class ShearerGHW2 {
public static void main(String[] args) {
System.out.println("List of 100 random 3 digit numbers");
Random rand = new Random();
for(int i = 1; i <= 100; i++) {
int rNum = rand.nextInt((999 - 100) + 1) + 100;
System.out.println(rNum);
}
}
}
Explanation / Answer
class KentChavisHw2
{
public static void main (String[] args)
{
//Write a Java application that generates a 3-digit random number 100 times.
// Display the output for each of the generated numbers
// and the sum of all 100 numbers
int numOfRandom = 100;
int[] ranArr = new int[100];
//fill array with random numbers
for (int pos = 0; pos < ranArr.length; pos++)
{
//assign a random number 100-999 inclusive to each element in array
ranArr[pos] = (int)((Math.random() * (1000 - 100)) + 100);
}//end for loop
//print table
int row = 0;
int sum = 0;
System.out.println("The output for 100 random numbers that are 3 digits"
+ " is as follows:");
System.out.print(" | ");
for ( int i = 0; i < ranArr.length; i++)
{
//print each random number in the array
System.out.printf("%4d", ranArr[i]);
sum = sum + ranArr[i];
//hard return after 10 random numbers
if (row == 9)
{
System.out.println(" | ");
if (i != ranArr.length - 1)
{
System.out.print(" | ");
}//end if for println
row = -1;
}//end if for row==9
row += 1;
}
System.out.println("sum = " + sum);
}//end main method
}//class KentChavisHw2
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.