I am trying to simulate a dice game experiment. The goal is to find the average amount of rolls it will take to get the same value of a die to show in the wanted amount of consecutive rolls.
My program asks the user how many times the user wants to run the program. So it will run the loop, then stop after they get their answer, then show the amount of throws it took. Then it will repeat as many times as the user specified.
I want to take the totalThrows from each experiment and add each totalThrows together then divide by my variable turns to get the average amount of throws it would take.
I am having some trouble getting the sum of all the totalThrows. And I can only get the last totalThrow. I would appreciate it if any of you could give some suggestions on how to resolve this. I think an array could help but I haven't learned arrays in class yet.
Here is my code.
public static void main(String[] args) {
// WRITE main's CODE HERE
Scanner keyboard = new Scanner(System.in);
Random randomNumber = new Random();
int value, turns=0, nSides, rollLength; //declare variables
int totalThrows=0, roll=0, count=0,finish=0;
//ask for input
System.out.println("Please enter the number of sides (2, 4, or 6): ");
nSides = keyboard.nextInt();
System.out.println("Enter the value sought. Must be in the range [1," + nSides + "]: ");
value = keyboard.nextInt();
System.out.println("Enter the length of the run.\n" + "Remember, the bigger it is the longer it will take to find it");
rollLength = keyboard.nextInt();
System.out.println("Enter number of times to run the experiment:");
turns = keyboard.nextInt();
System.out.println("\n");
do
{
//Countinue loop until count = rollLength
while(count!=rollLength){
roll = randomNumber.nextInt(nSides)+1;
totalThrows++; //will increment after every roll
//When roll comes up as a watched value I want to increment count by one
if(roll==value){
count++; //This should stop until count is my rollLength
}
else if (roll!=value){ //When an unwanted roll comes up start over
count=0;
}
}
//finish counts how many times the experiment was successful
if (count==rollLength){
finish++;
}
System.out.println("\n");
//Display totalThrows it took until rollLength variable occurs
System.out.println("Your total rolls is: "+ totalThrows);
} while(finish!=turns); //This will repeat the experiment
}
}
Simply declare another variable up top:
int averageThrows = 0;
Add to this value each time the loop ends:
do {
// ...
averageThrows += totalThrows;
} while( finish != turns );
And then divide it by the number of turns:
averageThrows /= turns;
That ought to do it for you.
Related
So I wrote this code and I wrote " int number = input.nextInt(); " in it as an experiment. The program does exactly what I want it to, but I don't understand why this works. The variable is not used at all later on in the program, but if I remove it, the program stops working. Any ideas? My code below:
import java.util.Scanner;
/*
* Name: Ki
*/
public class Countdown {
public static void main(String[] args) {
//Create a Scanner object to accept the input from user
Scanner input = new Scanner(System.in);
// Prompt the user to enter starting number, I just set it to 5 because
// that's what the program had as standard input.
System.out.println("Enter the beginning number: ");
// I don't know how this works. I had this here as an experiment, but
// the program now doesn't work without it so I guess I'll leave it here.
int number = input.nextInt();
// sets max countdown value
int i=5;
// Make a loop that makes the program countdown until it reaches 2
while(i>1)
{
System.out.print(i + " ... \n");
i--;
}
// Makes the program print 1 without dots and print stopped at the end
if (i==1) System.out.println(i);
System.out.print("Stopped");
}
}
int number = input.nextInt();
// sets max countdown value
// Make a loop that makes the program countdown until it reaches 2
while(number>1)
{
System.out.print(number + " ... \n");
number--;
}
// Makes the program print 1 without dots and print stopped at the end
if (number==1) System.out.println(number);
System.out.print("Stopped");
Here you create Scanner, but it doesn't do anything for the user yet.
Scanner input = new Scanner(System.in);
With nextInt() the program will wait for the user input.
int number = input.nextInt();
But after that you always use i, which is set to 5.
I guess you want to use the input number as the starting number. Change the later half to this:
// You can remove: int i=5;
while(number>1)
{
System.out.print(number + " ... \n");
number--;
}
// Makes the program print 1 without dots and print stopped at the end
if (number==1) System.out.println(number);
System.out.print("Stopped");
I'm trying to ask user to type how many numbers will be inputted and enter the values then add all the values.
import java.util.Scanner;
public class sum {
static Scanner sc = new Scanner(System.in);
public static void main(String[] args){
int counter = 1;
int values = 0;
int times;
System.out.println("How many numbers will you input?: ");
times = sc.nextInt();
while(counter == times){
System.out.println("Enter your number: ");
values = values + sc.nextInt();
counter ++;
}
System.out.println("Your sum is " + values);
}
}
Your logic for the while loop is incorrect.
while(counter == times)
will only be true if counter and times have the same value. So if you would want to input two numbers, your while loop wouldn't even get executed. What you want is for the while loop to run until counter == times. So, your logic should be
while(counter != times)
Furthermore, you should start your counter at zero, instead of one. This is because it now means that you already inputted one number, which you didn't.
Alternatively, you could use the following snippet
while (sc.hasNextInt()) {
values += sc.nextInt()
}
This simple loop will go through all the integers inputted in the command line one by one, until there is no next integer (you type for example a letter).
In that case, you don't need to ask the user how many numbers he/she will input, as you will check it yourself.
User inputs numbers one by one and then once they type in an invalid number (has to be from 1-200) the program calculates the average of the numbers that were inputted.
I'm just wondering what would the code be for this. I know the one for inputting one piece of data. Example would be:
`Scanner in = new Scanner(System.in);
String numberOfShoes = "";
System.out.println("Enter the number of shoes you want: (0-200) ");
numberOfShoes = in.nextLine();`
this is just an example, but this time I want the user to input a lot of numbers. I know I'm going to include a loop somewhere in this and I have to stop it once it contains an invalid number (using a try catch block).
* I would also like to add that once the user inputs another number it always goes to the next line.
Just use a while loop to continue taking input until a condition is met. Also keep variables to track the sum, and the total number of inputs.
I would also suggest having numberOfShoes be an int and use the nextInt() method on your Scanner (so you don't have to convert from String to int).
System.out.println("Enter your number of shoes: ");
Scanner in = new Scanner(System.in);
int numberOfShoes = 0;
int sum = 0;
int numberOfInputs = 0;
do {
numberOfShoes = in.nextInt();
if (numberOfShoes >= 1 && numberOfShoes <= 200) { // if valid input
sum += numberOfShoes;
numberOfInputs++;
}
} while (numberOfShoes >= 1 && numberOfShoes <= 200); // continue while valid
double average = (double)sum / numberOfInputs;
System.out.println("Average: " + average);
Sample:
Enter your number of shoes:
5
3
7
2
0
Average: 4.25
It added 5 + 3 + 7 + 2 to get the sum of 17. Then it divided 17 by the numberOfInputs, which is 4 to get 4.25
you are almost there.
Logic is like this,
Define array
Begin Loop
Accept the number
check if its invalid number [it is how u define a invalid number]
if invalid, Exit Loop
else put it in the array
End Loop
Add all numbers in your array
I think you need to do something like this (which #Takendarkk suggested):
import java.util.Scanner;
public class shoes {
public void main(String[] args){
int input = 0;
do{
Scanner in = new Scanner(System.in);
String numberOfShoes = "";
System.out.println("Enter the number of shoes you want: (0-200) ");
numberOfShoes = in.nextLine();
input = Integer.parseInt(numberOfShoes);
}while((input>=0) && (input<=200));
}
}
you can use for loop like this
for(::)
{
//do your input and processing here
if(terminating condition satisified)
{
break;
}
}
I have just written my first java program for a class I am taking which is used to give a student graduation information based on the credits for each class remaining. I have gotten everything to work except the required entry to check for negative values. Please see below and let me know if you have any ideas. Thanks in advance.
package txp1;
import java.util.ArrayList;
import java.util.Scanner;
public class txp1 {
public static void main(String[] args) {
// TODO code application logic here
System.out.println("Welcome to the University Graduation Calculator!");
System.out.println();
System.out.println("This calculator will help determine how many terms "
+ "you have remaining and your tuition total based upon credits"
+ " completed per semester.");
System.out.println();
double tuitionpersem = 2890;
System.out.println("We will begin by entering the number of credits for"
+ " each class remaining toward your degree.");
double sum = 0;
ArrayList<Double> credit = new ArrayList<>();
{
System.out.println("Please enter the number of credits for each individual class on a separate line and then press enter, Q to quit:");
Scanner in = new Scanner(System.in);
double number = 0;
number = Integer.parseInt(in.nextLine());
if (number <= 0);
{
System.out.println("The number of credits must be greater than zero!");
}
while (in.hasNextDouble()) {
credit.add(in.nextDouble());
}
for (int i = 0; i < credit.size(); i++) {
sum += credit.get(i);
}
System.out.println("Total credits remaining: " + sum);
}
int perterm = 0;
System.out.println("How many credits do you plan to take per term? ");
Scanner in = new Scanner(System.in);
perterm = Integer.parseInt(in.nextLine());
if (perterm <= 0);
{
System.out.println("The number of credits must be greater than zero!");
}
double totterms = sum / perterm;
totterms = Math.ceil(totterms);
System.out.print("Your remaining terms: ");
System.out.println(totterms);
double terms = (totterms);
System.out.print("The number of months to complete at this rate is: ");
System.out.println(6 * terms);
double cost = terms * 2890;
System.out.println("The cost to complete at this rate is: " + cost);
}
}
double number = 0;
number = Integer.parseInt(in.nextLine());
if (number <= 0);
The ";" at the end of if statement is the end of it. You are not doing anything with the result of number <=0. I believe you meant it to be like:
if (number <= 0){
//operations….
}
Notice that you create number of type double, then assign an int (parsed from String) to it. You can use nextDouble method to get a double directly, and if you plan this number to be an Integer anyway then use type int instead of double and nextInt instead of parsing. For more information about parsing from input, check Scanner documentation.
Your if statements terminate if you put a semi colon at the end of them. Effectively ending your logic right there. The program basically checks the condition and then moves on. Which in turn executes your second statement regardless of what number <= 0 resolves to.
//Does not get expected results
if (number <= 0);
{
//Gets executed regardless of condition
System.out.println("The number of credits must be greater than zero!");
}
//Gets expected results
if (number <= 0)
{
//Gets executed only if the condition returns true
System.out.println("The number of credits must be greater than zero!");
}
Edit: Changed due to some helpful input.
2nd Edit: I would also consider putting a loop in your code that makes the user re-enter input to get the desired value. If you put in a negative value your code will just spit the error message and keep running which can make you scratch your head. Unless your teacher isn't grading on that then forget all of what I just said. =p
So I've run into a kind of ridiculous predicament with one of my new projects. One of my assignments is to develop a game, and the player is given the option to be able to heal their hero a maximum of four times to max health. I've assigned a health value, assigned a command value so it recognizes when the player wants to heal, but I'm kind of stuck on how to limit the user to using the heal command only four times and how to restore their health back to full.
I was reading a different post on stackoverflow that seemed to have some relevance to my issue, although I couldn't quite figure out how to adjust it to my needs.
Scanner sc = new Scanner(System.in);
int number;
do {
System.out.println("Please enter a positive number!");
while (!sc.hasNextInt()) {
System.out.println("That's not a number!");
sc.next(); // this is important!
}
number = sc.nextInt();
} while (number <= 0);
System.out.println("Thank you! Got " + number);
Any advice or even direct help would be much appreciated! Thanks in advance!
Edit: Four times they can heal maximum in one game session. So once they use the heal command once, they can only use it three times, and so on and so on. The user inputs an integer in order to call the heal command up, in this case I prompt them for a decision and they simply input the number 0.
Basically what i can understand from your question is that you want the above code to be executed a maximum of 4 times i.e. if the user calls the method 1 time execute it, 2 times execute it and so on... But if it is called the fifth time you don't want the code to be executed.This can be achieved by maintaining a counter for example as shown below
public class Q
{
public static void main(String[] n)
{
Q1 ob =new Q1();
ob.myMethod();
System.out.println("One time");
ob.myMethod();
System.out.println("two time");
ob.myMethod();
System.out.println("three time");
ob.myMethod();
System.out.println("Fourth time");
ob.myMethod();
}
}
As you can see i have called the method 5 times. Now lets see how to restrict the user from getting or making only 4 calls to the method
class Q1
{
int counter=0;
public void myMethod()
{
if(counter<4)
{
Scanner sc = new Scanner(System.in);
int number;
do
{
System.out.println("Please enter a positive number!");
while (!sc.hasNextInt())
{
System.out.println("That's not a number!");
sc.next(); // this is important!
}
number = sc.nextInt();
} while (number <= 0);
System.out.println("Thank you! Got " + number);
counter++;
}
else
{
System.out.println("A maximum of 4 times of healing is allowed");
}
}
}