-- I am to write a program that prompts for N which is number of dice to roll and M for number of times to roll. I must repeat M times N6 or six sided die and compute and record the total sum of rolls. Using an array i must report how many times along with a percentage each possible total from 6 to 6N occurred.
Here is my code so far, i cannot get it to compile, and i think im going about it completely wrong, we only have one professor that teaches java, and he is not good at explaining things and always seems to be in a hurry if we ask questions. This is my second division class, and i learned barely anything the first semester.
////////////////////////////////
import java.util.Random;
import java.util.Scanner;
public class Lab1
{
public static Scanner in = new Scanner (System.in);
public static void main (String[] args)
{
int dice = 0;
int roll = 0;
while (true)
{
System.out.print ("How many dice do you roll?");
dice = in.nextInt();
}
System.out.print ("How many Times do you want to roll?");
roll = in.nextInt();
}
int dicetotal = Dicecount (dice); //Error message. dice cannot be resolved to Variable//
for (int i = 0; i< roll; i++)
System.out.println (Dicecount (dice));
}
}
public static int Dicecount ( int dice);
{
int dicetotal = 0;
for (int x = 0: x < dice; x++)
{
int rollcount = (int) (1+6* (Math.random()));
dicetotal+=rollcount;}
return dicetotal;
}
}
Properly format your code. This will help you find that the 6 lines starting with:
int dicetotal = Dicecount (dice);
Are not within a function block, and need to be.
You also have a colon instead of a semi-colon in this line (~7th from the bottom):
for(int x = 0; x < dice; x++){
Fixing these errors will allow your code to successfully compile - but that doesn't mean that it will do what you want it to do. Since this is homework, you'll be expected to find these issues and at least do initial troubleshooting on them yourself.
Two other problems this code appears to have:
1) In Java method names should always start with a lower-case letter. Here you have a method called dicecount. This is an invalid name and will confuse the Java compiler.
2) On the line where you declare the Dicecount method, you have a semicolon right at the end. This is a syntax error and will cause your code not to compile or behave incorrectly. The reason for this is that the semicolon is essentially telling the compiler that the current line is a complete statement. But it isn't finished, you still need to declare the body of the method.
So my advice is to change this line public static int Dicecount ( int dice); to read like this public static int dicecount(int dice). That is, remove the leading capital letter, and get rid of the semicolon at the end.
Related
I am making a game where the user gets to pick the number of die for each roll. Right now my code is processing the users input correctly, but it only randomly generates the last number, the other numbers are 0. (For example if the user input 4 the roll would appear : [0,0,0,3]
Does anyone know how to get all the numbers to generate random numbers?
Here is my main:
public class game
{
public static void main(String[] args)
{
int play = 1, sum = 0;
int[] wins = new int[15];
while ((play == 1) && (sum < 15))
{
sum = 0;;
int roll = 0;
Config die= new Config();
//starts configuration
die.hand();
System.out.println("\nHere is your roll:\n");
die.get();
}
}
Here is my configure class:
import java.util.Scanner;
import java.util.Random;
import java.util.Arrays;
class Config
{
public static int Dice;
int i;
public void hand()
{
System.out.println("\nLet's Configure the Game...\n");
String file = "Config.txt";
Scanner scan = new Scanner(System.in);
//configures number of dice in hand
System.out.println("Enter the number of dice you would like in your hand (1-5): ");
int hand_count = scan.nextInt();
int[] Dice = new int[hand_count];
System.out.println("Here is your roll: \n");
Random random= new Random();
for (i = 0; i<hand_count - 1; i++);
{
Dice[i] = random.nextInt(6) + 1;
System.out.println(Arrays.toString(Dice));
}
System.out.println("\nNow lets play the game...\n");
//s.close();
}
public int get()
{
return Dice;
}
}
for (i = 0; i<hand_count - 1; i++);
{
Dice[i] = random.nextInt(6) + 1;
System.out.println(Arrays.toString(Dice));
}
You have a semi-colon at the end of the first line of this for loop, resulting in your loop having no contents. Get rid of the semi-colon, and move your opening curly brace onto the same line as the for loop, i.e.
for (i = 0; i<hand_count - 1; i++) {
// do cool stuff
}
The answer by sunrise is good. But I suggest using ThreadLocalRandom instead of java.util.Random. Plus, your code has other issues to resolve.
ThreadLocalRandom
Using the ThreadLocalRandom class is thread-safe in case you ever use background threads. And a single random-number generator per thread is established, available automatically for re-use, so less overhead for repeated use.
Like java.util.Random, ThreadLocalRandom offers some nifty methods for generating a series of numbers as a stream for use in modern Java. We can shorten the code to a single-line.
int countDice = 3;
// Bounds of random number are inclusive, exclusive. So (1,7) for six-sided dice.
int[] results = ThreadLocalRandom.current().ints( countDice , 1 , 7 ).toArray();
System.out.println( "results = " + Arrays.toString( results ) );
When run:
results = [4, 6, 4]
Other issues
Variable names should start in lowercase. So public static int Dice; should be public static int dice;.
Class names start in uppercase, by convention. So public class game should be public class Game.
Your class design is disorganized. A key goal of object-oriented programming (OOP) is to more clearly model the entities being represented within your app. So I suggest you create a Die class to represent each die. That class should have a roll method that generates a new value.
In another class, instantiate some of these Die objects. Collect those instances in a collection named dice. Then for each round of your game, call roll on each die.
I was tempted to write more code for you, but this is obviously homework I'll go no further.
I need a program to randomly generate a number, and then out put that number of x's, on there own line, until it outputs a line of 16 x's, and then it will stop. So far my program generates a number but never stops outputting. I'm sure this is my error but not sure what needs to change. Here is my code at this moment.
import java.util.Random;
public static void main(String[] args)
{
toBinary();
randomX();
}
public static void randomX()
{
Random num = new Random();
int ran = num.nextInt(16+1);
int xs = ran;
while(xs <= 16)
{
System.out.print("x");
}
}
Your version has a number of small issues. Here's a suggested set of revisions.
// create your random object outside the method, otherwise
// you're instantiating a new one each time. In the long run
// this can cause awkward behaviors due to initialization.
public static Random num = new Random();
public static void randomX(){
int ran;
do {
ran = 1 + num.nextInt(16); // move the +1 outside unless you actually want 0's
int counter = 0;
while(counter++ < ran) {
System.out.print("x");
}
System.out.println(); // add a newline after printing the x's in a row
} while(ran < 16);
}
The biggest issue is that you need two loops, an outer one for generating new numbers and an inner one for printing the current number of x's.
A secondary problem was that your loop was checking for numbers <= 16. All of your values are <= 16, so it was an infinite loop.
Additional suggestions found in the comments.
To approach this, think of the loops you might need.
You need to print x a certain number of times, that's a loop. I also introduce a variable to keep track of this printing.
You need to keep printing until you hit 16. That's another loop.
public static void randomX(){
Random num = new Random();
int xs = 0;
//This loop keeps going until you reach 16
while(xs <= 16){
xs = num.nextInt(16+1);
int x = 0;
//This loop keeps going until you've printed enough x's
while (x < xs)
{
System.out.print("x");
x++;
}
System.out.println("")
}
}
You can use a auxiliary counter to manage the loop and increase it to exit the loop.
int i = 0;
while (i<xs){
System.out.print("x");
i++;
}
You can check more about java loops here:
Tutorial about java while
I have an array with 2 spots in it(it must have 2 spots in the beginning ). i need to get user input and double the array when user enters more than the array can hold. Also Upon entering -1 the user input should stop. The array must also not accept duplicates.
i don't know how to have the not accept duplicates and end the program when the user entters -1 while still doubling the array every time it fills up.
Here's what i have so far but its flawed and wont run properly.
public class GroupArrays {
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
int [] numbers = new int[2];
int x;
int n=0;
for( int i = 0; i<numbers.length; i++){
System.out.println("Please enter number");
int number = input.nextInt();
while ( input.hasNextInt() )
{
x = input.nextInt();
if ( n == numbers.length )
{
int[] h;
h = new int[ 2*numbers.length ];
for ( int i1 = 0; i1 < numbers.length; i1++ )
h[i1] = numbers[i1];
numbers = h;
}
if(x == -1){
break;
}
numbers[n] = x;
n++;
}
for ( int i1 = 0; i1 < numbers.length; i1++ )
System.out.println( numbers[i1] );
}
}
I can figure out how to do all the things individually but it becomes difficult when i have to do them all to 1 array and do user input.
PS. I feel like i have made this more complicated than it needs to be.
I'm only give you hints on how to solve the problem, and on how to write code that is easier to understand and maintain, even (and most importantly) by yourself.
Split the code in methods, doing simple tasks. Don't try to write everything as a giant piece of code.
The pseudo code of the algorithm would be
loop
ask and get input number
if (number is -1)
break out of the loop
else if array already contains number
print error message
else
if no space left in array
array = copy of array with doubled length
store number in next available index in array and increment the next available spot index
end of loop
print the array
Now, you can see that there are things that can be implemented easily as separate methods:
ask and get input number
check if array already contains number
copy of array with doubled length
print the array
Start by writing the signature of these simple methods, without implementing them. Then write the algorithm by calling these methods.
Then implement the simple methods one by one and test them one by one. You can do that, for now, by just writing a main method that calls them with hard-coded arguments, and see if they do what you expect them to do.
Once every of them is written and tested, test the main algorithm. If you made a mistake, iterate, by re-testing the methods you had to modify.
While coding all the methods, choose names that indicate clearly what the variables represent, and what the methods do, even if they're long. For example, nextAvailableIndex is much much clearer than x. Using good names helps everyone, including you, to understand the code and find bugs.
Also, indent the code strictly, as you type. The code you posted is not indented correctly, which makes it difficult to understand its structure. Stick to 4 spaces as indentation level, and always use curly braces around the body of your if, for, etc. ALways place them after the if/for, and not on the next line. Be consistent.
public class GroupArrays {
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
int [] numbers = new int[2];
int x;
int n=0;
for( int i = 0; i<numbers.length; i++){
System.out.println("Please enter number");
int number = input.nextInt();
while ( input.hasNextInt() )
{
x = input.nextInt();
if ( n == numbers.length )
{
int[] h;
h = Arrays.copyOf[numbers,2*numbers.length ]; //change
}
if(x == -1){
break;
}
numbers[n] = x;
n++;
}
for ( int i1 = 0; i1 < numbers.length; i1++ )
System.out.println( numbers[i1] );
}
}
Use Arrays.copyOf(array_name,array_length); to create new arrays with varying lengths.
Birthday probability problem
here is the algorithm which i follow, bit i still face problem. The algorithm is
To simplify the problem, we make the assumption that each day of the year (except February 29) is equally likely for a birthday. We will only consider 365 days in a year.
When generating a random birthday for a person, generate a random integer in the range 0-364, each number will represent an individual day in a year (0 for January 1st, and 364 for December 31st). We will use zero-based numbers to match array indexing.
When performing a single simulation, remember you only need to find one pair of matching birthdays to make the simulation count. That is, as soon as you determine that two people have the same birthday you can stop the current simulation and start the next simulation.
To ensure that everyone’s program behaves the same (so that we can auto-grade everyone’s submission), you will need to create a new Random object for each simulation run, and you will need to seed the Random object with the number of the run you are simulating (the first simulation run will use the integer 1 as the seed, the second run will use 2, etc.). You need to create a new Random object per simulation run, not per random number needed [do not use the Math.random() method in this program].
During one simulation, you will need to keep track of the days which ``correspond to someone’s birthday, or alternatively keep track of the number of birthdays that occur on any given day. There are several structures that we studied in this module of the MOOC that could be used to easily solve this problem. You are free to pick the structure of your choice. Note that the goal is to simply determine if two birthdays land on the same date.
When returning the final result, return the percentage in the range 0.0 – 100.0.
enter code here
import java.util.HashSet;
import java.util.Random;
import java.util.Scanner;
import java.util.Set;
public class Logic {
public static void process(int size, int count)
{
int number = 0;
Set<Integer> bdays = new HashSet<>();
int x[] = new int[size];
Random random = new Random();
random.setSeed(1);
int matches = 0;
boolean out = false;
for (int i = 0; i < count; i++) {
for (int j = 0; j < size; j++) {
number=(random.nextInt(365)+1);
}
for (int j = 0; j < count; j++) {
if (bdays.contains(number)) {
matches++;
}
else
{ bdays.add(number);
out = true;
break;}
if (out) {
out = false;
break;
}
}
}
double prob = 100*(double) matches / count;
System.out.println("The probability for two students to share a birthday is " + prob + ".");
}
public static void main(String[] args) {
Scanner inp = new Scanner(System. in );
System.out.println("How many students?");
int num = inp.nextInt();
System.out.println("How many times?");
int times = inp.nextInt();
process(num,times);
}
}
I suspect there are a few things wrong, but here's the first one: You're always adding number to bdays as soon as you assign number. You then later check to see if number is in bdays, which of course it will be - thus why you get the 100% match rate. What you need to do is:
Pick number
Check if number is already in bdays, and increment the counter if it is
Add number to bdays
alright so i have to write a class and driver that has the user input the number of dice and the number of rolls. and then i have to make an array based off the number of dice * 6. but i get errors. like arrayindexoutofboundsexception.
after i make the array i have to fill it with random numbers and use a histogram to display the program. so the program should look like this
Please give any positive help here, im new to this programing this and i would love to learn more. also i cant seem to figure out if statements for the Y/N area to start the program
Welcome to the dice-rolling simulator!
Do you wish to run a simulaton? Y/N: x
that was an invalid option. Please try again.
Do you wish to run a simulation? Y/N: y
How many dise di you wish to roll? 2
How many rolls to you wish to make? 100000
2:######
3:####
4:###########
5:#####
6:##
7:#
8:
9:##########
10:###
11:##############
12:######
//I had to you # signs because * would not work here
here is my program updated! how do i create the histogram?
package dice;
import java.util.Scanner;
import java.util.Random;
public class Dice
{
public static Scanner in = new Scanner (System.in);
private int dice = 0;
private int roll = 0;
private int start;
private int[] diceAr;
private int[] rollAr;
private int simDice;
private String star = "*";
//****************************************************************
public Dice()
{
System.out.println("Welcome to the dice-rolling simulator!\n");
System.out.println("Do you wish to run a simulation? Y/N; ");
//start = in.nextInt();
while (true) {
System.out.print ("How Many Dice Do You Want To Roll? ");
dice = in.nextInt();
simDice = (dice * 6)-1;
diceAr = new int[simDice];
if (dice > 0)
break;
}
while (true) {
System.out.print ("How Many Times Do You Want To Roll? ");
roll = in.nextInt();
rollAr = new int[roll];
if (roll > 0)
break;
}
}
//**********************************************
// public void display()
// {
//
for ( int i = 0; i < simDice; i++)
// {
// diceAr[i] = (int)(Math.random()* simDice);
//
// }
// for(int i = 0; i<simDice; i++)
// {
// System.out.println((i + dice) + ". " + diceAr[i]);
// }
//
// }
//*********************************************************
public void display(int diceAr[], int simDice, int roll)
{
for(int i=0; i < simDice; i++)
{
diceAr[i] = (int) (Math.random()* simDice);
}
for(int i=0; i < roll; i++)
{
}
}
}
Judging from the wording of the questions the program asks and the sample histogram you give, it appears the assignment is to write a program to simulate rolling N dice M times and then make a histogram of the results (i.e. the sum of the numbers on the dice on each roll) of the rolls. So if you enter 3 dice and 100 rolls, it should be as if you rolled 3 dice by hand 100 times.
Even aside from the ArrayIndexOutOfBoundsException issue, that is not what your code is doing. Since this is admitted homework I'm not going to give any code, at least not at this point. But I do have some suggestions/questions that might help you think about the problem better and perhaps you can show us how you've changed your code after thinking about it.
First, consider actually doing the task manually. Find two or three dice and roll them, say, 20 times, and make a histogram of the result on paper. You may find just doing that by itself will give you lots of insight into what your program will have to do and keep track of.
Next, here are some questions that might help focus your thinking:
If you are rolling 2 dice, what's the lowest possible result of a roll? What's the highest?
If you are rolling 3 dice, what's the highest and lowest possible result of a roll?
If you are rolling N dice, what's the highest and lowest possible result of a roll?
When you simulate a roll, how do you determine what the result of the roll is?
What array should you track those results in and how big should it be?
How do you track the results in such a way that you can make a histogram later?
What, if anything, besides the results do you need to store?
Think this all over, do the "experiment" manually, and then get back to us with what changes you've made to your program and what new questions you may have.
You're declaring diceAr to be size 'dice', but then indexing it with a variable which goes up to 'simDice', which = dice * 6.