I need to sum the points after each round. When I do it it doesn't work. It just outputs the point system under the if statements. Help and an explanation would be very helpful! Thank you from an intro Java coder.
public class J1 {
public static void main(String args[]) {
// create random object
java.util.Random rand = new java.util.Random();
java.util.Scanner scanner = new java.util.Scanner(System.in);
// check next int value
System.out.println("Wall height: " + rand.nextInt(10));
double height = rand.nextInt(10);
System.out.println("Distance from wall: " + rand.nextInt(20));
double dist = rand.nextInt(20);
for(int i = 1; i > 0; i++) {
System.out.println("Set a lanuch angle between 0 and 90: ");
double angle = scanner.nextDouble();
System.out.println("Set a lanuch speed: ");
double speed = scanner.nextDouble();
double point;
double a;
double b;
double c;
double d;
//double e;
double y;
a = dist*(Math.tan(Math.toRadians(angle)));
b = 9.81*(dist*dist);
c = (speed * Math.cos(angle)) * (speed * Math.cos(Math.toRadians(angle)));
d = 2*c;
y = a - (b/d);
System.out.println("Your max height is " +y+ " high");
double space;
space = height - y;
if(space <= 3 && space > 0) {
System.out.println("You just made it! ");
point = 0 - 1 + 3;
System.out.println("You have " +point+ " points.");
}
if (space > 3 && space <= 6) {
System.out.println("Aww. Plenty of room!");
point = 0 - 1 + 5;
System.out.println("You have " +point+ " points.");
}
if(space <= 0 && space >= -3) {
System.out.println("So close!");
point = 0 - 1 - 2;
System.out.println("You have " +point+ " points.");
}
if (space < -3) {
System.out.println("Terrible aim!");
point = 0 - 1 - 4;
System.out.println("You have " +point+ " points.");
}
}
System.out.println("Your total points: " +point);
}
}
The declaration of the point variable would need to occur outside of the for loop for it to be accessible for printing at the end of the code.
It also appears the for(int i = 1; i > 0; i++) { ... } loop will run indefinitely, which means the System.out.println("Your total points: " +point); line at the end will never be reached. You would need to fix the for loop so it only runs a limited amount of times.
The points after each round are never added to the grand total in the if sections, you would need to change the statement so that point += instead of point =.
I have added a few comments in the code below so you can see which changes have been made. I have also closed the scanner at the end as it is common practice, and fixed the code indentation for clarity purposes:
public class J1
{
public static void main( String args[] )
{
// create random object
java.util.Random rand = new java.util.Random();
java.util.Scanner scanner = new java.util.Scanner(System.in);
// check next int value
System.out.println("Wall height: " + rand.nextInt(10));
double height = rand.nextInt(10);
System.out.println("Distance from wall: " + rand.nextInt(20));
double dist = rand.nextInt(20);
double point = 0; //ADD THIS LINE
for(int i = 1; i < 10; i++) //CHANGED SO THAT i < 10 INSTEAD OF i > 0
{
System.out.println("Set a lanuch angle between 0 and 90: ");
double angle = scanner.nextDouble();
System.out.println("Set a lanuch speed: ");
double speed = scanner.nextDouble();
//double point; *** REMOVE THIS LINE ***
double a;
double b;
double c;
double d;
//double e;
double y;
a = dist*(Math.tan(Math.toRadians(angle)));
b = 9.81*(dist*dist);
c = (speed * Math.cos(angle)) * (speed * Math.cos(Math.toRadians(angle)));
d = 2*c;
y = a - (b/d);
System.out.println("Your max height is " +y+ " high");
double space;
space = height - y;
if(space <= 3 && space > 0)
{
System.out.println("You just made it! ");
point += 0 - 1 + 3; //ADDED += INSTEAD OF =
System.out.println("You have " +point+ " points.");
}
if(space > 3 && space <= 6)
{
System.out.println("Aww. Plenty of room!");
point += 0 - 1 + 5; //ADDED += INSTEAD OF =
System.out.println("You have " +point+ " points.");
}
if(space <= 0 && space >= -3)
{
System.out.println("So close!");
point += 0 - 1 - 2; //ADDED += INSTEAD OF =
System.out.println("You have " +point+ " points.");
}
if(space < -3)
{
System.out.println("Terrible aim!");
point += 0 - 1 - 4; //ADDED += INSTEAD OF =
System.out.println("You have " +point+ " points.");
}
}
System.out.println("Your total points: " +point);
scanner.close(); //ADD THIS LINE
}
}
Related
I am trying to write a program that allows a user to enter in a number of random grades they want to display along with the sum, average, minimum and maximum of the generated list. The grades range from 60 - 100.
The program is printing the min properly and the sum is adding up the previously generated sum along with the newly generated one. How can I change it so that it give the correct output for the minimum and so that is stops adding the previou sum to the new one? Any help would be appreciated.
The image link for the output shows the minimum output issue. The min should be 66.0 but it says 59.0.
output
import java.util.Scanner;
public class A03C
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("How many scores? ");
int howMany = input.nextInt();
double score = 0;
double sum = 0;
double average = 0;
double max = 0;
double min = 60;
while (howMany > 0)
{
for (int i = 1; i <= howMany; i++)
{
score = 60 + (int)(Math.random() * ((100 - 60) +1));
if (letterGrade(score));
sum += score++;
average = (sum/howMany);
if (score > max)
max = score;
if (score < max)
min = score;
}
System.out.println("Sum: " + sum);
System.out.println("Average: " + average);
System.out.println("Max: " + (max - 1));
System.out.println("Min: " + (min - 1));
System.out.println("How many scores? ");
howMany = input.nextInt();
}
}
public static boolean letterGrade(double score)
{
if (score >= 92.0)
System.out.println(score + " is an A");
else if (score >= 83.0)
System.out.println(score + " is a B");
else if (score >= 75.0)
System.out.println(score + " is a C");
else
System.out.println(score + " is an F");
return false;
}
}
Just clean the sum variable after the execution, also I changed the return of the letterGrade to true:
import java.util.Scanner;
public class A03C {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("How many scores? ");
int howMany = input.nextInt();
double score = 0;
double sum = 0;
double average = 0;
double max = 0;
double min = 60;
while (howMany > 0) {
for (int i = 1; i <= howMany; i++) {
score = 60 + (int) (Math.random() * ((100 - 60) + 1));
if (letterGrade(score))
sum += score++;
average = (sum / howMany);
if (score > max)
max = score;
if (score < max)
min = score;
}
System.out.println("Sum: " + sum);
System.out.println("Average: " + average);
System.out.println("Max: " + (max - 1));
System.out.println("Min: " + (min - 1));
System.out.println("How many scores? ");
sum = 0;
howMany = input.nextInt();
}
}
public static boolean letterGrade(double score) {
if (score >= 92.0)
System.out.println(score + " is an A");
else if (score >= 83.0)
System.out.println(score + " is a B");
else if (score >= 75.0)
System.out.println(score + " is a C");
else
System.out.println(score + " is an F");
return true;
}
}
Before continue, i definitely think that you should read #joe C comment.
As i understand you are a beginner, i will explain the changes i did.
import java.util.Scanner;
public class A03C
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("How many scores? ");
int howMany = = input.nextInt();
double score = 0;
double sum = 0;
double average = 0;
double max = 60;
double min = 100;
while (howMany > 0)
{
for (int i = 1; i <= howMany; i++)
{
score = 60 + (int)(Math.random() * ((100 - 60) +1));
letterGrade(score);
sum += score++;
average = (sum/howMany);
if (score > max)
max = score;
if (score < min)
min = score;
}
System.out.println("Sum: " + sum);
System.out.println("Average: " + average);
System.out.println("Max: " + (max - 1));
System.out.println("Min: " + (min - 1));
System.out.println("How many scores? ");
howMany = input.nextInt();
}
}
public static void letterGrade(double score)
{
if (score >= 92.0)
System.out.println(score + " is an A");
else if (score >= 83.0)
System.out.println(score + " is a B");
else if (score >= 75.0)
System.out.println(score + " is a C");
else
System.out.println(score + " is an F");
}
}
Starting with the function letterGrade. Since the function always return false and just prints a sentence, you can replace boolean to void.
Another mistake you did was that if you want to find max and min, the variables shall take the inverse of you want. So the variable max shall take the minimum variable (60) and the maximum value (100).
Finally, in order to change variables max and min you must compare the new value to their current value. This is, to change min value, for example, you have to compare score with current min.
Hope it helps.
I'm trying to half the input if it % 12 == 0, but if it isn't then you multiply it by 3 and add 1 onto the sum.
The question that I'm working off is: http://i.imgur.com/VzuPtZJ.png
With the code I have currently(which is below), if I enter 12, like in the question I start off with 6, but then the results begin to go wrong and then they go insanely wrong with values in the millions and negative millions etc.
import java.util.*;
public class sheet12t3
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("Enter a number: ");
int aNumber = Integer.parseInt(in.nextLine());
hailstone(aNumber);
}
public static void hailstone(int x)
{
int count = 1;
int max = 0;
String results = "Hailstone series for the number " + x + " is ";
while (x >= 1)
{
if (x % 12 == 0)
x = x / 2;
else
x = 3 * x + 1;
count++;
results += + x + ", ";
if (x > max)
max = x;
}
results += "a total of " + count + " numbers in this sequence with a maximum value of " + max;
System.out.print(results);
}
}
The question says divide by two if the number is even. But you divide by 2 only when it is dividable by 12.
Change this line
(x % 12 == 0)
to
(x % 2 == 0)
And change while (x >= 1) to while (x > 1)
Here is the code you are looking for:-
import java.util.*;
public class sheet12t3
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("Enter a number: ");
int aNumber = Integer.parseInt(in.nextLine());
hailstone(aNumber);
}
public static void hailstone(int x)
{
int count = 1;
int max = 0;
String results = "Hailstone series for the number " + x + " is ";
while (x > 1)
{
if (x % 2 == 0)
x = x / 2;
else
x = 3*x + 1;
System.out.print(x+" ");
max++;
}
}
}
I'm working on a coin flip assignment and I have the majority of it functioning properly (albeit in a less elegant fashion compared to the code I see on here).
I'm trying to find a way to tell the user which number appears most in their flips, and if heads are assigned to even #s, and tails to odd #s, which one came up the most. I'm looking for suggestions to implement these features.
Here is the code thus far:
import java.io.*;
import java.util.*;
public class coinFlip {
public static void main(String[] args) throws IOException {
// declare in as a BufferedReader; used to gain input from the user
BufferedReader in;
in = new BufferedReader(new InputStreamReader(System.in));
//declare variables
int flips;
int anArray[];
int x;
int r;
int counter1 = 0;
int counter2 = 0;
int counter3 = 0;
int counter4 = 0;
int counter5 = 0;
int counter6 = 0;
int counter7 = 0;
int counter8 = 0;
int counter9 = 0;
int counter10 = 0;
System.out.println("How many times would you like to flip your coin?");
flips = Integer.parseInt(in.readLine());
if (flips > 1000) {
System.out.println("Invalid input, restart program!");
}
if(flips <= 1000) {
System.out.println("You want to flip " + flips + " times");
anArray = new int[flips];
for(x = 0; x < flips; x++) {
r = (int) Math.round(Math.random()*9)+1;
anArray[x] = r;
System.out.println(anArray[x]);
if (anArray[x] == 1) {
counter1 += 1;
}
else if (anArray[x] == 2) {
counter2 += 1;
}
else if (anArray[x] == 3) {
counter3 += 1;
}
else if (anArray[x] == 4) {
counter4 += 1;
}
else if (anArray[x] == 5) {
counter5 += 1;
}
else if (anArray[x] == 6) {
counter6 += 1;
}
else if (anArray[x] == 7) {
counter7 += 1;
}
else if (anArray[x] == 8) {
counter8 += 1;
}
else if (anArray[x] == 9) {
counter9 += 1;
}
else if (anArray[x] == 10) {
counter10 += 1;
}
}
System.out.println("\n You rolled 1 " + counter1 + " times.");
System.out.println("You rolled 2 " + counter2 + " times.");
System.out.println("You rolled 3 " + counter3 + " times.");
System.out.println("You rolled 4 " + counter4 + " times.");
System.out.println("You rolled 5 " + counter5 + " times.");
System.out.println("You rolled 6 " + counter6 + " times.");
System.out.println("You rolled 7 " + counter7 + " times.");
System.out.println("You rolled 8 " + counter8 + " times.");
System.out.println("You rolled 9 " + counter9 + " times.");
System.out.println("You rolled 10 " + counter10 + " times.");
}
}
}
import java.io.*;
import java.util.Random;
public class CoinFlip {
public static void main(final String[] args) throws IOException {
// declare in as a BufferedReader; used to gain input from the user
final BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
//declare variables
System.out.println("How many times would you like to flip your coin?");
final int flips = Integer.parseInt(in.readLine());;
if (flips > 1000) {
System.out.println("Invalid input, restart program!");
return;
}
System.out.println("You want to flip " + flips + " times");
final int[] counters = new int[10],
side = new int[2];
int r=0,x,max=0;
final Random rand = new Random();
for(x = 0; x < flips; ++x) {
r = rand.nextInt(10);
System.out.println(r+1);
counters[r]++;
}
for ( x = 0; x < counters.length; ++x )
{
System.out.println("You rolled " + (x+1) + " " + counters[x] + " times.");
if ( counters[x] > max )
{
max = counters[x];
r = x+1;
}
side[x%2] += counters[x];
}
System.out.println(r + " was rolled most.");
System.out.println("You rolled " + side[0] + " heads and " + side[1] + " tails." );
}
}
Using loops, as shown in another answer, will make life much easier.
There is a more critical logic error in your code:
You round the output of Math.random(), which gives a float between 0 and 1, and round that to get an integer. The following table shows what output you'll get from your code in respect to the RNG:
| Math.random() output | Resulting Integer |
| 0 ~ 0.04999 | 0 |
| 0.05 ~ 0.14999 | 1 |
| ...... | ..... |
| 0.95 ~ 0.99999 | 10 |
See the problem? 0 and 10 appear only half as much as the other numbers.
You should either floor() the output, or use Random.nextInt() to generate a uniform distribution of ints.
This would make your life much easier:
int counter[10];
...
for(x = 0; x < flips; x++) {
r = (int) Math.round(Math.random()*9)+1;
anArray[x] = r;
System.out.println(anArray[x]);
counter[r-1]++;
}
for(i=1; i <= counter.length; i++)
System.out.println("You rolled " + i + " " + counter[i-1] + " times.");
For your other two problems, there's nothing to really "suggest". Just iterate over counter, remember the largest value, and add up the even and odd indices separately.
I need help with this problem. I am supposed to be making a program where I need to compare 10 stock prices and find the largest increase in a day in the numbers using the program. The program can only use for loops/if else and main method. I am using scanner to obtain the ints for the stock prices. Everytime i run the code, all i get is the last values that i put into the scanner. PLEASE HELP. Code below.
import java.util.Scanner;
//48 54 49 47 62 64 59 70 75 82
class Increase
{
public static void main (String [] args)
{
Scanner in = new Scanner(System.in);
final int Days = 10;
int highval = 0;
int lowval = 0;
int increase = 0;
int day = 0;
System.out.print("Enter the stock prices for " + Days + " number of days.");
int x = in.nextInt();
for (int i = 0; i < Days-1; i++)
{
int y = in.nextInt();
if (increase < (y - x));
{
increase = (y - x);
highval = y;
lowval = x;
day = i;
}
x = y;
}
System.out.println("The largest increase is " + increase);
System.out.println("from " +lowval + " to " + highval );
System.out.println("between days " + day + " and " + (day + 1));
}
}
The issue is with the ; in the line
if (increase < (y - x)); (empty assignment)
which is causing the below loop to be executed always.
{
increase = (y - x);
highval = y;
lowval = x;
day = i;
}
to fix change as below.
import java.util.Scanner;
class Increase
{
public static void main (String [] args)
{
Scanner in = new Scanner(System.in);
final int Days = 10;
int highval = 0;
int lowval = 0;
int increase = 0;
int day = 0;
System.out.print("Enter the stock prices for " + Days + " number of days.");
int x = in.nextInt();
for (int i = 0; i < Days-1; i++)
{
int y = in.nextInt();
if (increase < (y - x))
{
increase = (y - x);
highval = y;
lowval = x;
day = i;
}
x = y;
}
System.out.println("The largest increase is " + increase);
System.out.println("from " +lowval + " to " + highval );
System.out.println("between days " + day + " and " + (day + 1));
}
}
My problem is that whenever I try to compile and run my program, it says one of my arithmetic problems closer to the end of my code is dividing by zero. Now there is another problem. Whenever the user is prompted to enter the number of rolls, you can input a number and hit enter, but it just skips to the next line and nothing happens. Nothing else in the code happens.
* NOTE *
I can't use arrays in this assignment because it is not covered until the next section.
Here is my assignment here. This is what i'm supposed to be doing. I can't figure out what is going wrong here. My math seems to be correct but something is going wrong.
In short my assignment wants me to find the probability of two 11 sided dice being "rolled" the amount of times the user inputs. For example:
If the user says the dice it to be rolled 100 times it would output it something like this
2s: (insert Probability of having the sum of the 2 dice being 2 after 100 rolls)
3s: (insert Probability of having the sum of the 2 dice being 3 after 100 rolls)
4s: (insert Probability of having the sum of the 2 dice being 4 after 100 rolls)
5s: (insert Probability of having the sum of the 2 dice being 5 after 100 rolls)
and so on.
Here is my code so far:
public static void main(String[] args)
{
//Declare and initialize variables and objects
Scanner in = new Scanner(System.in);
Random randNum = new Random();
int match = 0; //Number of times sum of dice matches the current sum
int die1 = 0; //Random generated numbers
int die2 = 0;
int diceTotal2 = 0;
int diceTotal3 = 0;
int diceTotal4 = 0;
int diceTotal5 = 0;
int diceTotal6 = 0;
int diceTotal7 = 0;
int diceTotal8 = 0;
int diceTotal9 = 0;
int diceTotal10 = 0;
int diceTotal11 = 0;
int diceTotal12 = 0;
int sumOfDice = 0;
double probability2 = 0.0;
double probability3 = 0.0;
double probability4 = 0.0;
double probability5 = 0.0;
double probability6 = 0.0;
double probability7 = 0.0;
double probability8 = 0.0;
double probability9 = 0.0;
double probability10 = 0.0;
double probability11 = 0.0;
double probability12 = 0.0;
//Input: ask user for number of rolls and number of sides on a die
System.out.println("Number of Rolls: ");
int rolls = in.nextInt();
//***************************************************************************************
//Using nested loops, cycle through the possible sums of the dice.
//Roll the dice the given number of times for each sum.
//Count how many times the sum of the dice match the current sum being looked for.
//***************************************************************************************
//Loop to increment through the possible sums of the dice
//Loop to throw dice given number of times
for( int numberOfRolls = 1; numberOfRolls < rolls; numberOfRolls++)
{
die1 = randNum.nextInt(6);
die2 = randNum.nextInt(6);
sumOfDice = die1 + die2;
for( ; ; )
{
//Check if the sum of dice is equal to the given sum
if(sumOfDice == 2)
{
diceTotal2++;
probability2 = diceTotal2 / numberOfRolls;
}
else if(sumOfDice ==3)
{
diceTotal3++;
probability3 = diceTotal3 / numberOfRolls;
}
else if(sumOfDice ==4)
{
diceTotal4++;
probability4 = diceTotal4 / numberOfRolls;
}
else if(sumOfDice ==5)
{
diceTotal5++;
probability5 = diceTotal5 / numberOfRolls;
}
else if(sumOfDice ==6)
{
diceTotal6++;
probability6 = diceTotal6 / numberOfRolls;
}
else if(sumOfDice ==7)
{
diceTotal7++;
probability7 = diceTotal7 / numberOfRolls;
}
else if(sumOfDice ==8)
{
diceTotal8++;
probability8 = diceTotal8 / numberOfRolls;
}
else if(sumOfDice ==9)
{
diceTotal9++;
probability9 = diceTotal9 / numberOfRolls;
}
else if(sumOfDice ==10)
{
diceTotal10++;
probability10 = diceTotal10 / numberOfRolls;
}
else if(sumOfDice ==11)
{
diceTotal11++;
probability11 = diceTotal11 / numberOfRolls;
}
else if(sumOfDice ==12)
{
diceTotal12++;
probability12 = diceTotal12 / numberOfRolls;
}
}
}
System.out.println("Sum of Dice" + " " + "Probability");
System.out.println("2s: \t\t" + probability2 + "%");
System.out.println("3s: \t\t" + probability3 + "%");
System.out.println("4s: \t\t" + probability4 + "%");
System.out.println("5s: \t\t" + probability5 + "%");
System.out.println("6s: \t\t" + probability6 + "%");
System.out.println("7s: \t\t" + probability7 + "%");
System.out.println("8s: \t\t" + probability8 + "%");
System.out.println("9s: \t\t" + probability9 + "%");
System.out.println("10s: \t\t" + probability10 + "%");
System.out.println("11s: \t\t" + probability11 + "%");
System.out.println("12s: \t\t" + probability12 + "%");
//After all throws, calculate percentage of throws that resulted in the given sum
} //end main
As you already have a solution, I would present you with another one:
import java.util.Random;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int nRolls = 100, nDice = 6; // default values
Scanner in = new Scanner(System.in);
System.out.print("Number of throws: ");
nRolls = in.nextInt();
System.out.print("Number of sides on the dices: ");
nDice = in.nextInt();
int minSum = 2, maxSum = 2 * nDice;
int[] hist = new int[maxSum - minSum + 1];
Random rand = new Random();
for (int iter = 1; iter <= nRolls; iter++) {
int throw1 = 1 + rand.nextInt(nDice), throw2 = 1 + rand.nextInt(nDice);
int sum = throw1 + throw2;
hist[sum - minSum]++;
}
System.out.println("Number of rolls: " + nRolls);
System.out.println("Number of sides of the dice: " + nDice);
System.out.println("Sum of Dice Percentage");
for (int i = 0; i < hist.length; i++) {
System.out.println(String.format(" %2d %5.2f%%", i + minSum, hist[i] * 100.0 / nRolls));
// System.out.println(" " + (i+minSum) + " " + (hist[i]*100.0/nRolls);
}
in.close();
}
}
It shows you how to use arrays to solve this task. Each entry in the array holds the number of throws that came up with the corresponding sum. You always have 2*nDice - 1 possible sums (you can not reach 1 with two dices), so the size of the array is dependent on the number of sides on the dice.
Then you just iterate through all throws and add 1 to the corresponding histogram entry (note that I offset the histogram, so hist[0] corresponds to a sum of 2, hist[1] to a sum of 3, etc).
At the end, you can just calculate the percentage. (It's not a probability, it's the percentage that this sum occured in our simulation. If you make the number of rolls larger, this percentage will be an approximation of the probability.)
At the end, you just print it out. The String.format stuff is just for alignment of the values. If you are confused about it, just use
System.out.println(" " + (i+minSum) + " " + (hist[i]*100.0/nRolls);
instead.
Change numberOfRolls initiation to 1 instead of 0.
for( int numberOfRolls = 1; numberOfRolls <= rolls; numberOfRolls++) {
If numberOfRolls is 0, all your division operations results in divide by ZERO.
probability2 = diceTotal2 / numberOfRolls;