I am trying to print asterisks based on the number of times a dices side is rolled (all through an array). I am coming across an issue with the printing of the dice side (i) before the asterisks. Also, I'm getting two zeroes out of nowhere and don't know where they're coming from.
I'd appreciate the help.
My code:
public class Histogram {
public static void main(String[] args) {
// TODO Auto-generated method stub
int numRoles = 100;
int[] amountRoles = new int[7]; // amountRoles Holds the array
for (int i = 1; i < 7; i++)
amountRoles[i] = 0; // Set 0
{
for (int i = 0; i < numRoles; i++)
{
int die1 = (int)(Math.random()*6+1);
amountRoles[die1]++; // Increments
}
System.out.println("The die was rolled " + numRoles + " times, its six value's counts are:");
for (int i = 1; i < 7; i++)
{
System.out.print("Side " + i + " was rolled " + amountRoles[i]+ " times out of " + numRoles + ".");
// Prints each sides value (i) alongside with how many times it was rolled (amountRoles[i]).
System.out.println(); // Formatting Line
}
}
for (int i = 0; i < amountRoles.length; i++) // Iterates through amountRoles
{
for(int j = 0; j < amountRoles[i]; j++) // Loop through amountRoles[i]
{
System.out.print("" + "*");
}
System.out.println(i + " " + amountRoles[i]);
}
}
}
My output:
The die was rolled 100 times, its six value's counts are:
Side 1 was rolled 11 times out of 100.
Side 2 was rolled 19 times out of 100.
Side 3 was rolled 19 times out of 100.
Side 4 was rolled 17 times out of 100.
Side 5 was rolled 16 times out of 100.
Side 6 was rolled 18 times out of 100.
0 0 (Where are these zeroes coming from?)
***********1 11
*******************2 19
*******************3 19
*****************4 17
****************5 16
******************6 18
An example output I am aiming for:
[1] ******************* 19
[2] ************ 12
[3] ********************* 21
[4] ******************** 20
[5] ************* 13
[6] *************** 15
You're starting at zero?
also for the mid line
System.out.println(); // Formatting Line
the above can be removed and just add ln to the previous output.
I'd also use a variable to keep count of the string and then append it.
for (int i = 1; i < amountRoles.length; i++) // Iterates through amountRoles
{
String asterCount = "";
for(int j = 0; j < amountRoles[i]; j++) // Loop through amountRoles[i]
{
asterCount += ("*");
}
System.out.println("[" +i +"]"+ " "+ asterCount + " "+ amountRoles[i]);
}
Only answering your question an no other problems I see with the code, you are getting the 0 0 from int i = 0. Change this to int i = 1 and no more 0 0!
To get your values to print the way you need, you just need to simple move what you want to print before the * above the loop. In this case [i], and move the amount each roll was below the * loop. Code is below. This should fix your stated problems.
for (int i = 1; i < amountRoles.length; i++) // Iterates through amountRoles
{
System.out.print("[" + i + "]");
for(int j = 0; j < amountRoles[i]; j++) // Loop through amountRoles[i]
{
System.out.print("" + "*");
}
System.out.println(" " + amountRoles[i]);
}
Related
I am learning how to code and my teacher gave me an exercise to create a lottery program that generates 6 random numbers between 1 and 49 with no duplicates and one bonus number that could be a duplicate. My program generates all the numbers fine, but for some reason duplicates still appear. Could someone please explain why the code that checks for duplicates doesn't work, as I have been struggling to understand why it doesn't work. Please bear in mind that I'm a new programmer so try and keep explanations beginner friendly. Thanks in advance.
int[] lottonums = new int[6];
//Generates 6 random numbers between 1-49
for(int i = 0; i < lottonums.length; i++){
lottonums[i] = (int)(Math.random()* 49 +1);
}
//Checks for duplicates
for(int x = 0; x < 6; x ++){
for(int y = x + 1; y < 6; y ++){
while(lottonums[x] == lottonums[y]){
lottonums[y] = (int)(Math.floor(Math.random() * 49 + 1));
}
}
}
//Bonus ball, no checks for duplicates
int bonusBall = (int)(Math.random() * 49 + 1);
Arrays.sort(lottonums);
System.out.println("\nThe lottery numbers are: ");
for( int nu = 0; nu < lottonums.length; nu ++){
System.out.print(lottonums[nu] + " " );
}
System.out.println("\nThe bonus number is: " + bonusBall + "\n");
Best Way to have unique number is by using Set instead of array.
if you are not aware much about set have a look into it set TreeSet
Basically if you look at your code
//Checks for duplicates
for(int x = 0; x < 6; x ++){
for(int y = x + 1; y < 6; y ++){
while(lottonums[x] == lottonums[y]){
//below line does not gurrantee its going to insert unique number
//example [1,2,6,6] here at index 2 and 3 6 is there
//now you got this while checking duplicate
//after you are generating new random suppose new generated number is 2
// as you are not going back to check duplicate so it will be inserted
lottonums[y] = (int)(Math.floor(Math.random() * 49 + 1));
}
}
}
you can try the below solution using set
which fits yous requirement
// TreeSet will have unique element in sorted manner no need to sort again
TreeSet<Integer> set=new TreeSet<>();
int n=6;
while(set.size()<n-1)
{
set.add((int)(Math.random()* 49 +1));
}
//Bonus ball, no checks for duplicates
int bonusBall = (int)(Math.random() * 49 + 1);
System.out.println("\nThe lottery numbers are: ");
for( int nu :set){
System.out.print(nu + " " );
}
System.out.println("\nThe bonus number is: " + bonusBall + "\n");
}
public class Main {
public static void main(String[] args) throws IOException {
int i;
int sum=0;
for(i=1;i<=5;sum+=i++)
System.out.println(sum);
}
...
}
Actual Output:15
I don't know how it did the math?
The syntax for the for loop is:
for ( [ForInit] ; [Expression] ; [ForUpdate] ) Statement
and is basically equivalent with the following while loop:
[ForInit]
while (Expression) {
Statement
[ForUpdate]
}
That mean that all the following are the same:
for(i=1;i<=5;sum+=i++);
i = 1;
while (i <= 5) {
sum += i++;
}
i = 1;
while (i <= 5) {
sum += i;
i++;
}
for (i = 1; i <= 5; i++)
sum += i;
So it is calculating 1 + 2 + 3 + 4 + 5 = 15
What confuses you is the part
sum += i++
In this statement, first sum=sum+i gets calculated. Once sum has been calculated, value of i is incremented by 1.
Since the loop runs five times, previous value of sum gets added to current value of i, which keeps increases by 1.
Try printing out each iteration through the loop to help you visualise what is going on. Swap your for loop for this.
for(i=1;i<=5;sum+=i++)
{
System.out.println("sum = " + sum);
System.out.println("i = " + i);
}
In this code, the statement sum+ = i++ means sum = sum + i++ In this statement, every sum printed in the loop adds to one increment of i and when the loop ends it will display 15.
So it is calculating 0 + 1 + 2 + 3 + 4 + 5 = 15
Running a simple multiplication table but it's not giving me a desired output. I want each multiplication to be on different column separated with a little space. for example let 1 multiply numbers ranging from 1 to 12 should be on single column , 2 multiply numbers ranging from 1 to 12 on another column. I don't want all to be on just one column.
public class multiplicationTable{
public static void main(String[] args){
for(int i=1; i<=12;i++){
System.out.println(i);
for(int j=1; j<=12; j++){
int mult=i*j;
System.out.println(i + "*"9 + j +" = " + mult +" \t");
}
}
}
}
You should use System.out.print() method instead of System.out.println() method if you want to print stuff on the same line. Your program should look like this:
public class multiplicationTable
{
public static void main(String[] args){
for(int i=1; i<=12;i++){
System.out.println(i);
for(int j=1; j<=12; j++){
int mult=i*j;
System.out.print(i + "*"9 + j +" = " + mult +" \t");
}
System.out.println();
}
}
}
Whenever you call System.out.println(), it moves to the next line. So if you want to print all of the numbers times x on one line, you will have do something like this:
public static void main(String[] args){
// Print the headers
for (int i = 1; i <= 12; i++) {
// Two tabs because the calculations take up room on the console
System.out.print(i + "\t\t");
}
// Start at the next line
System.out.println();
// Let's define each multiplication as x * j
// For each j...
for (int i = 1; i <= 12; i++) {
// ...print all of the x's and their products
for (int j = 1; j <= 12; j++) {
System.out.print(j + " * " + i + " = " + j * i + "\t");
}
// Move to the next line for the next row of j's
System.out.println();
}
}
In this table:
1 * 1 = 1 2 * 1 = 2 3 * 1 = 3
What is changing? The first operand. Therefore, you need to nest the for loops
as the for loop for the first operand nested in the loop for the second operand to get the desired results.
Think about it this way: for each of the second operand, print all of the calculations for the first operands in a row. This way, you get the desired columns.
If this is not what you meant, please let me know in the comments.
Hope this helps.
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!
I am just very confused from this homework problem. I do not understand why the values of i and sum come out this way. I just do not understand the concept of the algorithm here, can someone please explain this?
int i = 0;
int sum = 0;
for(i=0; i < 5; i++)
{
sum += i;
}
System.out.println(i + "\n" + sum);
The output is:
5
10
----jGRASP: operation complete.
5 - because there are 5 iterations
10 - because the sum is 10 :)
Sum
Iteration 1: 0 + 0 = 0
Iteration 2: 0 + 1 = 1
Iteration 3: 1 + 2 = 3
Iteration 4: 3 + 3 = 6
Iteration 5: 6 + 4 = 10
Verification code
int i = 0;
int sum = 0;
for (i = 0; i < 5; i++) {
System.out.println(String.format(
"Iteration %s: %s + %s = %s", (i + 1), sum, i, (sum + i)));
sum += i;
}
This code :
int i = 0;
int sum = 0;
for(i=0; i < 5; i++)
{
sum += i;
}
System.out.println(i + "\n" + sum);
output in sum this : 0 + 1 + 2 + 3 + 4 which is equal to 10 and i the number of iterations = 5.
You have created a variable i with value of 0 and then incrementing it 5 times in for-loop. So you got i's value as 5.
Now the value of sum is 0+1+2+3+4 which is 10
Because you iterate through your loop, which makes i == 5, then print it,
Sum goes as below, you are adding i to the previously calculated sum
0 + 1 = 1
1 + 2 = 3
3 + 3 + 6
6 + 4 = 10
Try put your print command inside the loop, they you can see better what's going on.
The only non-obvious thing is (in my opinion): i will be 5, because you used i++, which also incremented i by 1 even though the body did not execute after the last iteration. Inside the body i only can be maximum 4.
int sum = 0; int i = 0;
for (i = 0; i < 5; i++)
{
sum += i;
if (i == 5)
System.out.println("never executed");
};
Other answers tell the other things.