Generate additional random number from array of 20 integers - java

I am having trouble with this, I need to generate an additional single random number that has the same 1-10 span. I already have the code for the random generator that produces my 20 integer array of random numbers but how do I generate a single random number in the same span within the same method. This is what I have so far and it keeps giving me random number 0: from my 20 integer array. Thanks in advance.
import java.util.Scanner;
import java.util.Random;
class Main{
public static final Random RND_GEN = new Random();
public int[] createNum(int[] randomNumbers) {
for (int i = 0; i < randomNumbers.length; i++) {
randomNumbers[i] = RND_GEN.nextInt(10) + 1;
}
for (int i = 0; i < 1 ; i++){
randomNumbers[i] = RND_GEN.nextInt(10) + 1;
}
return randomNumbers;
}
public void printNum(int[] randomNumbers){
for (int i = 0; i < randomNumbers.length; i++) {
System.out.println("Number " + i + " : " + randomNumbers[i]);
}
for (int i = 0; i < 1; i++){
System.out.println("Single # is: "+randomNumbers[i]);
}
}
public void searchArray(int[] randomNumbers, int numSearch) {
int count = 0;
for (int i : randomNumbers) {
if (i == numSearch) {
count++;
}
}
if (count == 0) {
System.out.println("Number # " + numSearch + " was not found!");
} else {
System.out.println("Number #" + numSearch + " occurred " + count + " times.");
}
}
public void run() {
Scanner inputReader = new Scanner(System.in);
int x = 1;
do {
int[] numbers = new int[20];
numbers = createNum(numbers);
printNum(numbers);
System.out.print("Restart Program?, Enter 1 for YES, 2 for NO: ");
x = inputReader.nextInt();
} while (x == 1);
}
public static void main(String[] args) {
Main go = new Main();
go.run();
}
}

This loop in printNum() looks suspicious:
for (int i = 0; i < 1; i++){
System.out.println("Single # is: "+randomNumbers[i]);
}
It will always print the first element of randomNumbers. It's not clear what you want, but if I had to guess it would be:
int i = RND_GEN.nextInt(randomNumbers.length);
System.out.println("Single # is: " + randomNumbers[i]);
which will print some random element of randomNumbers. Or perhaps:
int i = 1 + RND_GEN.nextInt(10);
System.out.println("Single # is: " + i);
which will print an independent random number between 1 and 10 (inclusive).
P.S. You have another one of those suspicious loops earlier in your code in createNum() as well. However, that one seems harmless in that it just assigns a second random number to randomNumbers[0].

Related

how do i get the code to print the integers i have entered instead of these numbers?

When I enter my 7 integers "1 2 3 4 2 6 2" it will print the correct number of occurrences. However it will print the numbers at "49 50 51 52 53 54 55"... What in my code is missing or what do I need to change in order to get it print the correct numbers?
public static void main(String[] args)
{
final int maxEntryCount = 7;
int [][] numbers = new int [maxEntryCount][2];
System.out.print("Enter " + maxEntryCount + " integers separated by spaces: ");
Scanner input = new Scanner(System.in);
for (int i = 0; i < maxEntryCount; i++) {
numbers[i][0] = (input.next().charAt(0));
}
for (int i = 0; i < maxEntryCount; i++) {
for (int j = 0; j < maxEntryCount; j++) {
if (numbers[i][0] > 0 && numbers [j][0] == numbers[i][0]) {
numbers[i][1]++;
if (j > i) {
numbers[j][0] = 0;
}
}
}
}
for (int i = 0; i < maxEntryCount; i++) {
if (numbers[i][0] > 0) {
System.out.println("Number " + numbers[i][0] + " occurs " + (int) numbers[i][1] + " times");
if (numbers[i][0] == 1) {
System.out.println("Number " + numbers[i][0] + " occurs " + (int) numbers[i][1] + " time");
}
}
}
}
Just change your loop where you are getting the user input to:
for (int i = 0; i < maxEntryCount; i++) {
numbers[i][0] = (input.nextInt());
}
In your code you were reading the input as character. When you type 1 then it will take its ASCII value instead of 1.
I changed it to input.nextInt() which is used to take int as input.

Generate Random Number - Put into List - Print List

I have a program that generates a list of numbers and computes all into a total and separates them into three different list. One being all of the numbers, and the other two are even and odd and then prints the even and odd array-list.
or some reason when I try to print out the two list, it only prints the first couple of numbers in the ArrayList giving my no error messages.
My Code:
import java.util.Random;
import java.util.ArrayList;
public class Projects {
public static void main(String [] args) {
Random Generate = new Random ();
ArrayList<Double> List = new ArrayList<>();
ArrayList<Double> Even = new ArrayList<>();
ArrayList<Double> Odd = new ArrayList<>();
double number;
double total = 0;
double totalEven = 0;
double totalOdd = 0;
double averageWhole;
double averageEven;
double averageOdd;
System.out.println("Generating Numbers:");
for (int Repeater = 0; Repeater < 10; Repeater++) {
number = Generate.nextInt(100);
List.add(number);
}
System.out.println("Loaded... " + "Putting Numbers Into List");
System.out.println();
for(int Insert = 0; Insert < 3; Insert++) {
System.out.println("Adding To List...");
}
System.out.println("List Completed!");
System.out.println();
System.out.println();
for (int x = 0; x < List.size(); x++) {
total += List.get(x);
//Complicated Code --- really big for loop try to simplify later.
if (List.get(x) % 2 == 0) {
Even.add(List.get(x));
}
else {
Odd.add(List.get(x));
}
}
System.out.println("Your Total Is: " + total);
System.out.println();
System.out.println();
System.out.println("Even Numbers:" + "\t" + "Odd Numbers");
for (int Output = 0; Output < Even.size() && Output < Odd.size(); Output++)
{
System.out.println(Even.get(Output) + "\t" + "\t" + Odd.get(Output));
}
averageWhole = total / List.size();
System.out.println("Average of All Numbers: " + "Average of All Even Numbers: "+ "Average of all Odd Numbers: " );
for (int averageE = 0; averageE < Even.size(); averageE++) {
totalEven = totalEven + Even.get(averageE);
}
averageEven = totalEven / Even.size();
for (int averageO = 0; averageO < Odd.size(); averageO++) {
totalOdd = totalOdd + Odd.get(averageO);
}
averageOdd = totalOdd / Odd.size();
System.out.print(averageWhole + "\t" + "\t" + "\t" + " " + averageEven + "\t" + "\t" + "\t" + "\t" + " " + averageOdd);
System.out.println();
System.out.println();
System.out.println("Command Complete...");
Sorry for it being so compacted - learning java - 2/3 weeks in -- Thanks!
When you are printing the odd and even numbers the condition in the loop will be met when the shorter list will be done, so the printing stops before printing all the numbers. You separate the printing to two separate loops.
for (int i = 0; i < Even.size(); i++) {
System.out.println(Even.get(i));
}
for (int i = 0; i < Odd.size(); i++) {
System.out.println(Odd.get(i));
}
As a side note, variables in Java should start with lowercase. Even, Odd, Output etc should be even, odd, output.
Another alternative to Guy's code that keeps the same format:
for (int Output = 0; Output < Even.size() || Output < Odd.size(); Output++) {
String even = "-";
if(Output < Even.size()){
even = Even.get(Output).toString();
}//end of if
String odd = "-";
if(Output < Odd.size()){
odd = Odd.get(Output).toString();
}
System.out.println(even + "\t" + "\t" + odd);
}

Getting the minimum and maximum values in a randomly generated array in java

import java.util.Random;
public class Java {
public static void main(String args[]) {
int arr[] = new int[10];
Random Rand = new Random();
int max = 0;
int min = arr[0];
for(int i = 0; i < 10; i++) {
int RandNum = Rand.nextInt(10);
arr[i] = RandNum;
if (i == 0) System.out.print("[");
System.out.print(arr[i] + " ");
if (i == 9) System.out.println("]");
if (RandNum>max) {
max = RandNum;
}
if (i > 0) {
if (RandNum < arr[0]) {
min = RandNum;
}
}
}
System.out.println("Minimum number: " + min);
System.out.println("Maximum number: " + max);
}
}
I could get the maximum value, but not the minimum.. please bear with me, I'm a beginner, I've tried comparing the min value with the first array value, but I'm not sure if the min value should be array[0] or just 0.
First, you need to make sure that the first number is treated as the minimum,to give it some initial value, like
if(i==0){
System.out.print("[");
min = RandNum;
}
This could be avoided by initializing min, with Integer.MAX_VALUE
Then, you need to compare with min, not array[0] like,
if(i>0){
if(RandNum<min){
min = RandNum;
}
}
Also, for what its worth, you could also do
System.out.println("Minimum number: " + Arrays.stream(arr).min());
System.out.println("Maximum number: " + Arrays.stream(arr).max());
When you set min, you set it to zero (it's the default value for the integers in an initialized array). As such, no number generated will ever be greater than it. Set min to something like:
min = Integer.MAX_VALUE;
And then check each newly generated number with each pass instead of skipping it for the first iteration of the loop.
You're also not checking the newly generated number with min, but with the first number of the array. Use this:
if(RandNum < min) /*do stuff*/;
Hope this helps!
You always comparing to arr[0] instead of comparing to "min".
you should write:
if(RandNum<min)
{
min = RandNum;
}
Notes:
Set min and max to first array position.
You don't need check if the current index of for loop is greater than 0, just check if min variable is greater than current random number. e.g if (min > number) min = number;
Using a more simple logic to print the vector.
Using your own code:
import java.util.Random;
public class App {
public static void main(String... args) {
int count = 10;
int arr[] = new int[count];
Random random = new Random();
int max = arr[0];
int min = arr[0];
for (int i = 0; i < count; i++) {
int number = random.nextInt(20);
arr[i] = number;
if (i == 0) {
System.out.print("Array: [ " + number + " ");
} else if (i == count - 1) {
System.out.println(number + " ]");
} else {
System.out.print(number + " ");
}
if (max < number) {
max = number;
}
if (min > number) {
min = number;
}
}
System.out.println("Minimum number: " + min);
System.out.println("Maximum number: " + max);
}
}
A more simple approach, using Arrays.toString:
import java.util.Arrays;
import java.util.Random;
public class App {
public static void main(String... args) {
int count = 10;
int array[] = new int[count];
int min = array[0], max = array[0];
final Random random = new Random();
for (int i = 0; i < count; i++) {
int number = random.nextInt(10);
array[i] = number;
if (min > number) {
min = number;
}
if (max < number) {
max = number;
}
}
System.out.println("Array: " + Arrays.toString(array));
System.out.println("Minimum number: " + min);
System.out.println("Maximum number: " + max);
}
}
Using Java Streams API (Java 8 or newer):
import java.util.Arrays;
import java.util.Random;
public class App {
public static void main(String... args) {
final int[] array = new Random().ints(10).toArray();
System.out.println("Arrays: " + Arrays.toString(array));
System.out.println("Minimum number: " + Arrays.stream(array).min());
System.out.println("Maximum number: " + Arrays.stream(array).max());
}
}
int min=0; // Define with cero
for(int i=0; i<10; i++)
{
// Logic of min
arr[i] = RandNum;
if(i ==0) // JUST in the first time
{
min=arr[0]
}
if(RandNum<min) // This inside your for
{
min = RandNum;
}
}
try this:
public static void main(String[] args) {
int arr[] = new int[10];
Random Rand = new Random();
int max=0;
int min=11;
for(int i=0; i<10; i++)
{
int RandNum = Rand.nextInt(10);
arr[i] = RandNum;
if(i==0) { System.out.print("["); }
System.out.print(arr[i] + " ");
if(i==9) { System.out.println("]"); }
if(RandNum>max)
{
max = RandNum;
}
if(RandNum<min)
{
min = RandNum;
}
}
System.out.println("Minimum number: " + min);
System.out.println("Maximum number: " + max);
}

Dice Roll Histogram with Loops

I have a problem in my class that I just can't figure out.
This is the question:
The purpose of this quiz is to reinforce the understanding of using loops and counting as well as reviewing the use of random numbers.
Modify the program below to print a histogram in which the total number of times the dice rolls equals each possible value is displayed by printing a character like # that number of times. Two dices will be used in each roll.
Example:
Histogram showing total number of dice rolls for each possible value.
Dice roll statistics (result varies):
2s: ######
3s: ####
4s: ###
5s: ########
6s: ###################
7s: #############
8s: #############
9s: ##############
10s: ###########
11s: #####
12s: ####
~~~~~~~~~~~~~~~~~~~~~
I haven't been able to get the program to print the histogram in the example above.
And this is what I have so far:
import java.util.Scanner;
import java.util.Random;
public class DiceStats {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
Random randGen = new Random();
int seedVal = 11;
randGen.setSeed(seedVal);
// FIXME 1 and 2: Set the seed to the Random number generator
int i = 0; // Loop counter iterates numRolls times
int numRolls = 0; // User defined number of rolls
// FIXME 3: Declare and initiate cariables needed
int numOnes = 0;
int numTwos = 0;
int numThrees = 0;
int numFours = 0;
int numFives = 0;
int numSixes = 0; // Tracks number of 6s found
int numSevens = 0; // Tracks number of 7s found
int numEights = 0;
int numNines = 0;
int numTens = 0;
int numElevens = 0;
int numTwelves = 0;
int die1 = 0; // Dice 1 values
int die2 = 0; // Dice 2 values
int rollTotal = 0; // Sum of dice values
System.out.println("Enter number of rolls: ");
numRolls = scnr.nextInt();
if (numRolls >= 1) {
// Roll dice numRoll times
for (i = 0; i < numRolls; ++i) {
die1 = randGen.nextInt(6) + 1;
die2 = randGen.nextInt(6) + 1;
rollTotal = die1 + die2;
// FIXME 4: Count number of sixs and sevens; complete the same for all other possible values
if (rollTotal == 1) {
numOnes = numOnes + 1;
}
if (rollTotal == 2) {
numTwos = numTwos + 1;
}
if (rollTotal == 3) {
numThrees = numThrees + 1;
}
if (rollTotal == 4) {
numFours = numFours + 1;
}
if (rollTotal == 5) {
numFives = numFives + 1;
}
if (rollTotal == 6) {
numSixes = numSixes + 1;
}
if (rollTotal == 7) {
numSevens = numSevens + 1;
}
if (rollTotal == 8) {
numEights = numEights + 1;
}
if (rollTotal == 9) {
numNines = numNines + 1;
}
if (rollTotal == 10) {
numTens = numTens + 1;
}
if (rollTotal == 11) {
numElevens = numElevens + 1;
}
else if (rollTotal == 12) {
numTwelves = numTwelves + 1;
}
System.out.println("Debugging: Roll " + (i+1) + " is " + rollTotal + " (" + die1 +
"+" + die2 + ")");
}
// Print statistics on dice rolls
System.out.println("\nDice roll statistics:");
// FIXME 5: Complete printing the histogram
System.out.println("1s: " + numOnes);
System.out.println("2s: " + numTwos);
System.out.println("3s: " + numThrees);
System.out.println("4s: " + numFours);
System.out.println("5s: " + numFives);
System.out.println("6s: " + numSixes);
System.out.println("7s: " + numSevens);
System.out.println("8s: " + numEights);
System.out.println("9s: " + numNines);
System.out.println("10s: " + numTens);
System.out.println("11s: " + numElevens);
System.out.println("12s: " + numTwelves);
}
else {
System.out.println("Invalid rolls. Try again.");
}
return;
}
}
Any help would be very appreciated.
Have a loop like this where you have your print statements.
Modify your code so that instead of taking new variables every time have them in a array so that you can loop through them.
import java.util.Scanner;
import java.util.Random;
public class DiceStats {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
Random randGen = new Random();
int seedVal = 11;
randGen.setSeed(seedVal);
// FIXME 1 and 2: Set the seed to the Random number generator
int i = 0; // Loop counter iterates numRolls times
int numRolls = 0; // User defined number of rolls
// FIXME 3: Declare and initiate cariables needed
int[] numValues=new int[12];
int die1 = 0; // Dice 1 values
int die2 = 0; // Dice 2 values
int rollTotal = 0; // Sum of dice values
System.out.println("Enter number of rolls: ");
numRolls = scnr.nextInt();
if (numRolls >= 1) {
// Roll dice numRoll times
for (i = 0; i < numRolls; ++i) {
die1 = randGen.nextInt(6) + 1;
die2 = randGen.nextInt(6) + 1;
rollTotal = die1 + die2;
// FIXME 4: Count number of sixs and sevens; complete the same for all other possible values
numValues[rollTotal]++;
System.out.println("Debugging: Roll " + (i+1) + " is " + rollTotal + " (" + die1 +
"+" + die2 + ")");
}
// Print statistics on dice rolls
System.out.println("\nDice roll statistics:");
// FIXME 5: Complete printing the histogram
for(int i=2;i<=12;i++)
{
System.out.print(i+"s: ");
for(int j=0;j<numVales[i];j++)
{
System.out.print("#");
}
System.out.println();
}
else {
System.out.println("Invalid rolls. Try again.");
}
return;
}
}
Let me know if you need clarification on the problem.
You can do something like this:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
//You can directly set the seed during the object creation.
Random random = new Random(System.currentTimeMillis());
// This array is used to keep the value of your dice (2 - 12)
int [] histogram = new int[13];
while(true) {
System.out.println("Enter number of rolls: ");
int numberOfRolls = scanner.nextInt();
//If you enter 0, you can simply terminate the program
if(numberOfRolls == 0) break;
for(int i = 0; i < numberOfRolls; i++) {
int rolledValue = (random.nextInt(6) + 1) + (random.nextInt(6) + 1);
histogram[rolledValue]++;
}
//Print the result to your console.
for(int i = 2; i < histogram.length; i++) {
System.out.print("Total: " + i + " ");
for(int j = 0; j <histogram[i]; j++) {
System.out.print("#");
}
System.out.println();
}
}
}
That code will have a result as below:
Enter number of rolls: 7
Total: 2
Total: 3 #
Total: 4
Total: 5 ##
Total: 6
Total: 7 ###
Total: 8
Total: 9
Total: 10 #
Total: 11
Total: 12
Looks like you're really close. You just need to print the number of # for each int variable you have. The following will do that for the numTwos:
char[] chars = new char[numTwos];
Arrays.fill(chars, '#');
String result = new String(chars);
System.out.println(result);
You can put the whole thing in a loop of 12 to print it for all of them.

Use an outer While Loop that is sentinel driven to ask the user if they wish to generate a new set of random numbers

This is what I have so far but for some reason the program states the operation is complete without allowing the user to enter 1 or 2 to continue or not. Thanks in advance..
My code:
import java.util.Random;
public final class Kidwell_Lab09 {
public static Random generator = new Random();
public static void main(String[] args) {
int x;
int[] randomNumbers = new int[20];
do
{
Random generator = new Random();
for (int i = 0; i < randomNumbers.length; i++){
int n = generator.nextInt(10)+1;
randomNumbers[i] = n;
}
for (int i = 0; i < randomNumbers.length; i++) {
System.out.println("Number " + i + " : " + randomNumbers[i]);
}
System.out.print("Do you wish to restart the program, Enter 1 for YES, 2 for NO: ");
x = generator.nextInt();
}
while ( x == 1 );
}
}
You should be reading the value from System.in rather than from generator.nextInt().
Here is the corrected code.
import java.util.Random;
public final class Kidwell_Lab09 {
public static Random generator = new Random();
public static void main(String[] args) {
int x;
int[] randomNumbers = new int[20];
Scanner inputReader = new Scanner(System.in);
do {
Random generator = new Random();
for (int i = 0; i < randomNumbers.length; i++) {
int n = generator.nextInt(10) + 1;
randomNumbers[i] = n;
}
for (int i = 0; i < randomNumbers.length; i++) {
System.out.println("Number " + i + " : " + randomNumbers[i]);
}
System.out.print("Do you wish to restart the program, Enter 1 for YES, 2 for NO: ");
x = inputReader.nextInt();
} while (x == 1);
}
}

Categories

Resources