Die Simulator nested loop issue - java

import java.util.Scanner;
public class DiceSimulator {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("How many dice do you want to roll: ");
int amountOfDie = input.nextInt();
System.out.println("");
// declare diceArray
Die[] diceArray = new Die[amountOfDie];
// create a new Die for each reference
int maxRoll = 0;
for (int i = 0; i < diceArray.length; i++) {
System.out.print("How many sides on die number " + (i + 1) + "" + ": ");
int numSides = input.nextInt();
diceArray[i] = new Die(numSides);
int minRoll = amountOfDie;
maxRoll += numSides;
}
int minRoll = amountOfDie;
// int[] sumArray = new int[maxRoll + 1];//to store sum
System.out.println("");
System.out.print("How many times do you want to roll: ");
int numRol = input.nextInt();
System.out.println("\nResults");
// ******** right here is where I'm having the issue.
for (int i = 0; i < numRol; i++) {
diceArray[i].roll();
// System.out.println(diceArray[i]);
int sum = 0;
for (int f = 0; f < numRol; f++) {
sum += diceArray[f].roll();
int[] sumArray = new int[maxRoll + 1];
sumArray[sum]++;
System.out.print("\t" + sum);
}
}
// for(Die d: diceArray){
// System.out.println(d);
// }
}
}
See commented line in code: // ******** right here is where I'm having the issue.
The for loop should spit out the sum of the rolls.
It just isn't spitting out the right values. I'm just curious where I went wrong? The program should ask the user how many rolls. This would go into the first for loop and the second would roll the dice that many times.

I think what you're trying to do is roll these dice a said number of times, keeping track of how often each total is reached, so you can print them at the end. Try this:
int[] sumArray = new int[maxRoll];
for (int i = 0; i < numRol; i++) {
int sum = 0;
for (Die d : diceArray) {
int roll = d.roll();
sum += roll;
System.out.print("\t" + roll);
}
System.out.println("\t:\t" + sum);
sumArray[sum-1]++;
}
for (int i = 0; i < sumArray.length; i++){
System.out.printf("%d: %d Rolls\n", i+1, sumArray[i]);
}
You can see it working here. Your most basic mistakes were:
Declare your sum array before you start calculating sums.
In the inner loop, iterate over your dice, one at a time, rolling, adding to the sum, and printing.
Print your sum and increment your count after the dice have been rolled.
If you roll two six sided dice 10 times with this algorithm, you'll get:
Results
4 3 : 7
5 5 : 10
2 2 : 4
6 5 : 11
1 1 : 2
6 5 : 11
6 5 : 11
1 2 : 3
2 1 : 3
3 5 : 8
1: 0 Rolls
2: 1 Rolls
3: 2 Rolls
4: 1 Rolls
5: 0 Rolls
6: 0 Rolls
7: 1 Rolls
8: 1 Rolls
9: 0 Rolls
10: 1 Rolls
11: 3 Rolls
12: 0 Rolls

You have a line that looks like this:
diceArray[i].roll();
The problem is that diceArray is only large as the number of dice you have. But you are trying to use it with an index of the number of rolls. This could cause an ArrayOutOfBoundsException.

Related

Needed to create a function thet recieves an array of 2 degits nums , Switch between the digits and print but got an error

Write a function that receives double-digit numbers, until a number that is not double-digit is received.
• For each number received the program will generate a reverse number and print it. For example : 67 will be printed 76.
• The program will print a count of some of the received numbers thet contains the digit 5 ​​in the digit
Unity (right digit).
I researched the error I got a couple of times but couldn't solve it, if you guys can help much appreciated.
public static void switchInput() {
Scanner star = new Scanner(System.in);
int x=0 , temp=0 , y=1 , i , b=0;
x= star.nextInt();
int[] Switch = new int[x];
//input
for(i=0 ; i<y ; i++){
System.out.println("insert num "+ y + " :");
temp= star.nextInt();
x++;
y++;
Switch[i]=temp;
if(temp<10||temp>99) {
y=i;
}
if(temp%10==5) {
b++;
}
temp=0;
}
star.close();
//Switch
int j , temp2 , temp3=0;
for(j=0 ; j<x ; j++) {
temp3=Switch[j]/10;
temp2=Switch[j]%10;
temp3+=temp2*10;
Switch[j]=0;
Switch[j]=temp3;
}
//print
for(int z = 0;z<x-1;z++) {
System.out.print(" "+Switch[z]+ " ");
}
System.out.println("Number of times 5 was used is : " + b);
}
I got the error :
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 44 out of bounds for length 44
at hagashaShadi.q1.switchInput(q1.java:37)
at hagashaShadi.q1.main(q1.java:67)
See x= star.nextInt(); here your providing size of array suppose its x=3
which means int[] Switch = new int[3]; but when you are running for loop you are getting like this Switch[4] which is out of bound for the array of size 3. So solution is to use either while loop and insert only when it satisfy the condition and it should break once it cross size of array or if you want to use for loop then break out of loop when i>length-of-array
Have a look at the below code for more understanding
public static void switchInput() {
Scanner star = new Scanner(System.in);
int i=0 , countDigit=0;
List<Integer> numList=new ArrayList<>();
boolean isTwoDigitNumber=true;
//Insert all input number of 2 digit
while(isTwoDigitNumber)
{
System.out.println("insert num "+ (i+1)+ " :");
int temp= star.nextInt();
if(temp%10==5){
countDigit++;
}
if(temp>10&&temp<99) {
numList.add(temp);
i++;
}else {
isTwoDigitNumber=false;
}
}
star.close();
//Switch
//reverse the number and print
for(int j=0 ; j<numList.size() ; j++) {
int num = numList.get(j), reversed = 0;
//System.out.println("Original Number: " + num);
// run loop until num becomes 0
while(num != 0) {
// get last digit from num
int digit = num % 10;
reversed = reversed * 10 + digit;
// remove the last digit from num
num /= 10;
}
System.out.println("reverse Number: " + reversed);
}
//print number of times 5
System.out.println("Number of times 5 was used is : "+countDigit);
}

Error when picking out unique numbers in an array

This is a problem in my textbook for my Java class where the user enters 10 integers. The program is supposed to read all integers and only display the unique numbers (not duplicated) as the output. I am having trouble understanding why my output is not picking up the last unique value in the array (5). Can anyone give some insight to this issue? Any help would be appreciated. (Since we are in the early stages of the class and understanding the language, our assignment is to complete this using a nested loop.)
-The output is:
Enter 10 numbers: 1 2 3 2 1 6 3 4 5 2
The number of distinct numbers is 5
The distinct numbers are: 1 2 3 6 4
-When it should be:
Enter 10 numbers: 1 2 3 2 1 6 3 4 5 2
The number of distinct numbers is 6
The distinct numbers are: 1 2 3 6 4 5
public class ch7e5{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter 10 numbers: ");
int[] numberArray = new int[10];
//create array for all numbers
int[] distinctArray = new int[10];
//create array for distinct numbers
int distinct = 0;
for (int i = 0; i < 10; i++)
numberArray[i] = input.nextInt();
distinctArray[0] = numberArray[0];
//first value will be distinct
for (int i = 1; i < numberArray.length; i++) {
//loop to go through remaining values in numberArray
boolean exists = false;
//create boolean
for (int j = 0; j < numberArray.length; j++) {
//loop to check if value exists already in distinctArray
if (numberArray[i] == distinctArray[j]) {
exists = true;
break;
//break out of inner loop
}
}
if (exists == false) {
//if value is unique then add it to the distinct array
distinct++;
distinctArray[distinct] = distinctArray[i];
}
}
//}
System.out.println("The number of distinct numbers is " + distinct);
System.out.print("The distinct numbers are: ");
for (int k = 0; k < distinct; k++)
System.out.print(distinctArray[k] + " ");
}
}```
There are 3 distinct numbers, 1, 2, and 3 are not any of them as they appear twice. The output should be 6 4 5. I'm not sure how you got 5 distinct numbers here, maybe you inputted them wrong? I would try not using a scanner at first and try putting the numbers in the array manually. Additionally, I would create a boolean array length 10 starting all true to record if numbers are distinct. If a number appears twice, the corresponding boolean in the array will be false. I will update this with code once i have written it.
EDIT: apparently having a duplicate does not delete it from the distinct list. If this is the case, please elaborate on the title.
Here is my code:
public class Main {
public static void main(String[] args) {
int inputs = 3;
int[] numberArray = new int[inputs];
int distinct = 0;
boolean[] mirror = new boolean[inputs];
//just setting up arrays
for(int i = 0; i < numberArray.length; i++) {
//numberArray[i] = i;
mirror[i] = true;
}
numberArray[0] = 1;
//finds out what numbers are not distinct
for (int x = 0; x < numberArray.length; x++) {
for (int y = 0; y < numberArray.length; y++) {
System.out.println("x is " + x);
System.out.println("y is " + y);
if(numberArray[x] == numberArray[y] && x != y) {
System.out.println(numberArray[x] + " is not distinct");
mirror[x] = false;//if current position in array matches any other position, number is not distinct
}
}
}
//calculates how many are distinct
for(int j = 0; j < inputs; j++) {
if(mirror[j]) {distinct++;}
}
//outputs text
System.out.println("The number of distinct numbers is " + distinct);
System.out.print("The distinct numbers are: ");
for(int k = 0; k < inputs; k++){
if(mirror[k]) {System.out.print(numberArray[k] + " ");}
}
}
}
The error was here
distinct++;
distinctArray[distinct] = distinctArray[i];
1, you should increment distinct after adding a number to distinctArray, and 2, you should have done distinctArray[distinct] = numberArray[i]. Right now, you're just putting what is possibly a 0 into distinctArray[distinct].
A shorter way to do it would be this
int[] distinctArray = Arrays.stream(numberArray).distinct().toArray();
System.out.println("The number of distinct numbers is " + distinctArray.length);
System.out.print("The distinct numbers are: ");
for (int d : distinctArray) System.out.print(d + " ");
Output:
Enter 10 numbers: 1 2 3 2 1 6 3 4 5 2
The number of distinct numbers is 6
The distinct numbers are: 1 2 3 6 4 5

Print a given number pattern from user input using nested for loop

I am new to programming. Am currently learning Java, on nested loop now, and got stuck.
So what I want to do is to write a program that takes an integer from user and
print lines, for example if user input was 4 then the result should be like:
1
1 2
1 2 3
1 2 3 4
Here is my code so far:
import java.util.Scanner;
public class Hello {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter number of rows:");
int number = input.nextInt();
for (int i = 1; i <= number; i++) {
System.out.println(i);
for (int j = 1; j <= i; j++) {
System.out.print(j + " ");
}
}
}
}
But it prints one extra line at the end, like:
1
1 2
1 2 3
1 2 3 4
1 2 3 4
And it is hard for me to figure out why.
I guess it is my first for loop but I don't know how to fix the for loop to get the result I want.
Any help will be appreciated. Thanks!
Don't print anything from the outer loop, only new line
for (int i = 1; i <= number; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(j + " ");
}
System.out.println();
}
Output
1
1 2
1 2 3
1 2 3 4
To avoid the trailing spaces of the other answers,
rather than printing i at the start of the loop, print 1.
Then start the inner loop from 2 and print a space before each value. And print a new line after the inner loop.
for (int i = 1; i <= number; i++) {
System.out.print("1");
for (int j = 2; j <= i; j++) {
System.out.print(" " + j);
}
System.out.println();
}
Prints:
1
1 2
1 2 3
1 2 3 4
The problem is printing a newline and i at the same time... just take care of the new line after your for loop. The inner loop can handle all the prints.
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter number of rows:");
int number = input.nextInt();
for (int i = 1; i <= number; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(j + " ");
}
System.out.println();
}
}
}
Let's us dry run it
at first you print
1
then newline
then j goes from 1 to 1 nut no newline now 2 is printed by i now newline
so result 1 2
again j goes like 1 , 2 but no newline so again 3 is printed by i then newline
so result 1 2 3
again j goes like 1 , 2, 3, but no newline so again 4 is printed by i then newline
so result 1 2 3 4
again j goes like 1 , 2, 3, 4 // this one is the extra line

Print a variable a n number of times in java

My project is to show lines with cardinals, from an initial number and
then varying this number to another number entered.
It starts by asking for a initial number of cardinals (the output must be "###" the number of times asked) and then ask for the final number of cardinals to add. So case, click here 5 initial cardinals and add 3, the program must show a line with 5, another with 6, another with 7 and another with 8 cardinals.
How do I add the cardinals? With if-else?
import java.util.Scanner;
public class P02Cardinais {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the number inicial of cardinals: ");
int numCardinais = keyboard.nextInt();
System.out.println("Enter the number of cardinals to add: ");
int numCardinaisAdd = keyboard.nextInt();
int i;
for (i = 0; i < numCardinais; i++) {
System.out.print("#");
} System.out.print(" - " + numCardinais);
keyboard.close();
}
}
Example of the output
(number inicial - 2 ; number to add - 3)
## - 2
### - 3
#### - 4
##### - 5
You need 2 loops
one for the number of lines from initial to initial+add
one for the number of # which has to be the index of first loop (limo of j is i)
for (int i = numCardinais; i <= numCardinais+numCardinaisAdd; i++) {
for (int j = 0; j<i; j++) {
System.out.print("#");
}
System.out.println(" - " + i); // new line and index
}

Dice Roll Histogram

I have a class question that I cannot seem to understand the logic for.
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, as shown below.
Histogram showing total number of dice rolls for each possible value.
Dice roll histogram:
2: ******
3: ****
4: ***
5: ********
6: *******************
7: *************
8: *************
9: **************
10: ***********
11: *****
12: ****
I do not understand what in the world this histogram is displaying. Its driving me insane and I cannot move forward with my logic if I do not understand what I am doing. I know this question has been asked before but it looks like they all have a specific number of dice roles they are going off of. I am not given a number and this is what is throwing me off. I know this is really a stupid question. But can anyone possibly explain to me what they mean by "Histogram showing total number of dice rolls for each possible value" what is defining this possible value? I am at a total loss... Any help is appreciated. Here is the code I have written 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 i = 0; // Loop counter iterates numRolls times
int numRolls = 0; // User defined number of rolls
int numOnes = 0; // Tracks number of 1's found
int numTwos = 0; // Tracks number of 2's found
int numThrees = 0; // Tracks number of 3's found
int numFours = 0; // Tracks number of 4's found
int numFives = 0; // Tracks number of 5's found
int numSixes = 0; // Tracks number of 6's found
int numSevens = 0; // Tracks number of 7's found
int numEights = 0; // Tracks number of 8's found
int numNines = 0; // Tracks number of 9's found
int numTens = 0; // Tracks number of 10's found
int numElevens = 0; // Tracks number of 11's found
int numTwelves = 0; // Tracks number of 12's found
int die1 = 0; // Dice values
int die2 = 0; // Dice 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;
// Count number of sixes and sevens
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("Roll " + (i+1) + " is " + rollTotal + " (" + die1 +
"+" + die2 + ")");
}
// Prints a histogram of the number of dice rolls
System.out.println("\nDice roll histogram:");
System.out.println("1's: " + numOnes);
System.out.println("2's: " + numTwos);
System.out.println("3's: " + numThrees);
System.out.println("4's: " + numFours);
System.out.println("5's: " + numFives);
System.out.println("6's: " + numSixes);
System.out.println("7's: " + numSevens);
System.out.println("8's: " + numEights);
System.out.println("9's: " + numNines);
System.out.println("10's: " + numTens);
System.out.println("11's: " + numElevens);
System.out.println("12's: " + numTwelves);
}
else {
System.out.println("Invalid rolls. Try again.");
}
return;
}
}
You can see where I entered the entry for histograms. I basically thought that I needed to edit my value given from the integers such as "numOnes" to asterisk but now I'm not certain... any help is appreciated!
EDITED CODE -
System.out.println("\nDice roll histogram:");
System.out.print("2's: ");
for(i = 0; i < numTwos; i++){
System.out.print("*");
}
System.out.println("");
System.out.print("3's: ");
for (i = 0; i < numThrees; i++);{
System.out.print("*");
}
System.out.println("");
System.out.print("4's: " );
for (i = 0; i < numFours; i++);{
System.out.print("*");
}
System.out.println("");
System.out.print("5's: ");
for (i = 0; i < numFives; i++);{
System.out.print("*");
}
System.out.println("");
System.out.print("6's: ");
for (i = 0; i < numSixes; i++);{
System.out.print("*");
}
System.out.println("");
System.out.print("7's: ");
for (i = 0; i < numSevens; i++);{
System.out.print("*");
}
System.out.println("");
System.out.print("8's: ");
for (i = 0; i < numEights; i++);{
System.out.print("*");
}
System.out.println("");
System.out.print("9's: ");
for (i = 0; i < numNines; i++);{
System.out.print("*");
}
System.out.println("");
System.out.print("10's: ");
for (i = 0; i < numTens; i++);{
System.out.print("*");
}
System.out.println("");
System.out.print("11's: ");
for (i = 0; i < numElevens; i++);{
System.out.print("*");
}
System.out.println("");
System.out.print("12's: ");
for (i = 0; i < numTwelves; i++);{
System.out.print("*");
}
System.out.println("");
}
OUTPUTS -
Enter number of rolls:
5
Roll 1 is 8 (2+6)
Roll 2 is 9 (6+3)
Roll 3 is 9 (5+4)
Roll 4 is 6 (4+2)
Roll 5 is 9 (6+3)
Dice roll histogram:
2's:
3's: *
4's: *
5's: *
6's: *
7's: *
8's: *
9's: *
10's: *
11's: *
12's: *
I can enter a larger number of rolls and I will get an asterisk for the 2's and it will increase like I need but it will not increase the rest of the numbers and they all only get one asterisk. What is keeping my code from properly increasing the amount of *'s? Iv been fighting with this for hours :/
"I do not understand what in the world this histogram is displaying."
Well, as you said:
"Histogram showing total number of dice rolls for each possible value"
The histogram:
2: ******
3: ****
4: ***
5: ********
6: *******************
7: *************
8: *************
9: **************
10: ***********
11: *****
12: ****
is a record of the rolls of a pair of six sided dice. The possible values of totaling a pair of dice range from 2 to 12. If you rolled them 100 times they might give these results.
This histogram shows that the value 6 was most frequently rolled (19 times) and 4 the least frequently rolled (3 times). If you counted up every * you'd know how many times the dice have been rolled.
You may think that a histogram must look like this:
But turn that sideways:
and imagine that the blue bars are *'s, the 100 - 150 label is a 2, and the 150 - 200 label is a 3, well then it starts to look like your histogram.
Either form is a histogram. They let you compare quantities (how many) of things that fall in different categories (kinds) of things.
A graphic chart is difficult to output from a program that is text based so instead it's asking you to display what is basicly ascii art:
If this was in a text file, and not program output, this could also be considered a form of tally. You can easily add new *'s as you receive new data. It's the same trick as this:
Hope that makes more sense.
SPOILER ALERT: If that helped and you'd like to take a crack at modifying the program yourself read no further. Otherwise...
This
System.out.println("\nDice roll histogram:");
System.out.println(" 1's: " + nManyStars(numOnes));
System.out.println(" 2's: " + nManyStars(numTwos));
System.out.println(" 3's: " + nManyStars(numThrees));
System.out.println(" 4's: " + nManyStars(numFours));
System.out.println(" 5's: " + nManyStars(numFives));
System.out.println(" 6's: " + nManyStars(numSixes));
System.out.println(" 7's: " + nManyStars(numSevens));
System.out.println(" 8's: " + nManyStars(numEights));
System.out.println(" 9's: " + nManyStars(numNines));
System.out.println("10's: " + nManyStars(numTens));
System.out.println("11's: " + nManyStars(numElevens));
System.out.println("12's: " + nManyStars(numTwelves));
and this
static String nManyStarsOld(int n) {
String result = "";
for (int i = 0; i < n; i++) {
result += "*";
}
return result;
}
should, if dropped in the right places, get your program to stop printing what it prints now which is this:
Enter number of rolls:
20
Roll 1 is 5 (2+3)
Roll 2 is 10 (4+6)
Roll 3 is 7 (5+2)
Roll 4 is 7 (5+2)
Roll 5 is 5 (1+4)
Roll 6 is 11 (6+5)
Roll 7 is 8 (3+5)
Roll 8 is 8 (2+6)
Roll 9 is 7 (1+6)
Roll 10 is 8 (3+5)
Roll 11 is 12 (6+6)
Roll 12 is 6 (2+4)
Roll 13 is 8 (6+2)
Roll 14 is 8 (4+4)
Roll 15 is 7 (1+6)
Roll 16 is 4 (2+2)
Roll 17 is 6 (5+1)
Roll 18 is 7 (6+1)
Roll 19 is 6 (1+5)
Roll 20 is 5 (1+4)
Dice roll histogram:
1's: 0
2's: 0
3's: 0
4's: 1
5's: 3
6's: 3
7's: 5
8's: 5
9's: 0
10's: 1
11's: 1
12's: 1
And instead, get it to print this:
Dice roll histogram:
1's:
2's:
3's:
4's: *
5's: ***
6's: ***
7's: *****
8's: *****
9's:
10's: *
11's: *
12's: *
Next time you post a question please include the current output along with the expected output.
If you feel like being a smarty pants there is actually a one line version of nManyStars():
static String nManyStars(int n) {
return new String(new char[n]).replace("\0", "*");
}
Inspired by this: https://stackoverflow.com/a/4903603/1493294
Also, if you have at least Java 11 you can trade in nManyStars(n) for "*".repeat(n)
Hope it helps
Iv got it all working. Thank you #CandiedOrange and #MadProgrammer for the help and guidance! Found that my histogram code was messed up with my for statements having a ; in an incorrect spot causing my for statement to not apply the * based on its process of running through the for statement and it was just printing a * as a normal print function. All is well. Thanks for all the help!

Categories