I am not sure if what I am asking is right, but originally i had this run 5 times in the main. however i felt that a do/while loop could do the same thing. But now I cannot get the array shotsMade to change from shotsMade[0] to shotsMade[1] etc, and the shotCount to store to it. It will only store the last run of the while loop. What can I change to make those 2 items increment so the methods still calculate the data correctly
import java.util.*;
public class Final {
public static void main(String[] args) {
int myGameCounter = 1;
int [] shotsMade = new int [5];
System.out.print("Enter Player's Free Throw Percentage: ");
Scanner input = new Scanner(System.in);
int percent = input.nextInt();
//Game
do{
System.out.println("Game " + myGameCounter + ":");
Random r = new Random();
myGameCounter++;
int shotCount = 0;
for (int i = 0; i < 10; ++i){
boolean in = tryFreeThrow(percent);
if (in) {
shotCount++;
System.out.print("In" + " ");
}
else {
System.out.print("Out" + " ");
}
}
System.out.println("");
System.out.println("Free throws made: " + shotCount + " out of 10");
System.out.println("");
shotsMade[0]= shotCount;// I need shotsMade[0] to change each loop, shotsMade[1], shotsMade[2], shotsMade[3], shotsMade[4]
} while (myGameCounter <=5);
System.out.println("");
System.out.println("Summary:");
System.out.println("Best game free throws made: " + max(shotsMade));
System.out.println("Worst game free throws made: " + min(shotsMade));
System.out.println("Total Free Throws Made: " + sum(shotsMade) + " " + "out of 50");
System.out.println("Average Free Throw Percentage: " + average(shotsMade) +"%");
}
public static boolean tryFreeThrow(int percent) {
Random r = new Random();
int number = r.nextInt(100);
if (number > percent){
return false;
}
return true;
}
public static int average (int nums[]) {
int total = 0;
for (int i=0; i<nums.length; i++) {
total = total + nums[i];
}
int average = total*10 / nums.length;
return average;
}
public static int sum(int nums[]) {
int sum = 0;
for (int i=0; i<nums.length; ++i) {
sum += nums[i];
}
return (int)sum;
}
public static int max(int nums[]) {
int max = nums[0];
for (int i=1; i<nums.length; i++) {
if (nums[i] > max)
max = nums[i];
}
return max;
}
public static int min(int nums[]) {
int min = nums[0];
for (int i=1; i<nums.length; i++) {
if (nums[i] < min)
min = nums[i];
}
return min;
}
}
Two things:
Move myGameCounter++; just below where you set shotsMade[]
Otherwise, you are increasing the game counter to 2 before the first game finished.
It should look like:
shotsMade[myGameCounter-1]= shotCount;
myGameCounter++;
} while (myGameCounter <=5);
Set shotsMade[myGameCounter-1]= shotCount; instead of shotsMade[0]= shotCount;
Otherwise, you are overwriting the value of shotsMade[0]
This way, you are re-using a counter as index for the array. Since myGameCounter will increase by one after each game (after you changed point 1) and it starts from 1, using myGameCounter - 1 will yield the correct index for your array shotsMade.
Related
I want to take the array of random values I've generated and print the aforementioned array with parentheses outside the longest run of the same number.
For example, if the array was [0,1,1,1,2,4,7,4] I'd like to receive 0(111)2474 as an output.
This is my code thus far.
import java.util.Random;
import java.util.Arrays;
/**
* Write a description of class ArrayRunner1 here.
*
* #author Ibrahim Khan
* #version (a version number or a date)
*/
public class ArrayRunner1 {
/**
* This method will generate my random numbers for my array.
* #param min minimum random value wanted
* #param max maximum random value wanted
* #return randomNum a random number between 1 and 6 inclusive
*/
public static int randInt(int min, int max) {
Random rand = new Random();
int randomNum = rand.nextInt((max - min) + 1) + min;
return randomNum;
}
public static void main(String[] args) {
System.out.println("\f");
//Part 1 - Generate a random array of length 40 with random 1-6 inclusive
int[] array1 = new int[40];
for (int i = 0; i < array1.length; i++) {
array1[i] = randInt(1, 6);
}
System.out.println(Arrays.toString(array1));
//Counts and RETURN: reports how many times each number is present
int counter1 = 0;
int counter2 = 0;
int counter3 = 0;
int counter4 = 0;
int counter5 = 0;
int counter6 = 0;
for (int i = 0; i < array1.length; i++) {
if (array1[i] == 1) {
counter1++;
}
if (array1[i] == 2) {
counter2++;
}
if (array1[i] == 3) {
counter3++;
}
if (array1[i] == 4) {
counter4++;
}
if (array1[i] == 5) {
counter5++;
}
if (array1[i] == 6) {
counter6++;
}
}
System.out.println("There are " + counter1 + " ones.");
System.out.println("There are " + counter2 + " twos.");
System.out.println("There are " + counter3 + " threes.");
System.out.println("There are " + counter4 + " fours.");
System.out.println("There are " + counter5 + " fives.");
System.out.println("There are " + counter6 + " sixes.");
//Counts the longest run of the same number. A run continues only when consecutive numbers have the same value.
//RETURN: The repeated number and the length of the run is then printed
int counter = 1;
int runMax = 1;
int runMin = 0;
int variableNum = 0;
int startCounter = 0;
int endCounter = 0;
for (int i = 0; i < array1.length - 1; i++) {
if (array1[i] == array1[i + 1]) {
counter++;
if (counter >= runMax {
runMax = counter;
runMin = i - counter + 1;
variableNum = array1[i];
startCounter = i - counter + 2;
endCounter = i + counter - 1;
}
} else {
counter = 1;
}
}
System.out.println("The longest run is " + runMax + " times and the number is " + variableNum + ". ");
System.out.println("The run starts at " + startCounter + " and ends at " + endCounter);
//Prints the array with parentheses outside the longest run, if there is more than one max run, use the last one.
}
}
try this code:
import java.util.Arrays;
import java.util.Random;
public class Snippet {
/**
* This method will generate my random numbers for my array.
*
* #param min
* minimum random value wanted
* #param max
* maximum random value wanted
* #return randomNum a random number between 1 and 6 inclusive
*/
public static int randInt(int min, int max) {
Random rand = new Random();
int randomNum = rand.nextInt((max - min) + 1) + min;
return randomNum;
}
public static void main(String[] args) {
System.out.println("\f");
// Part 1 - Generate a random array of length 40 with random 1-6
// inclusive
int[] array1 = new int[40];
for (int i = 0; i < array1.length; i++) {
array1[i] = randInt(1, 6);
}
System.out.println(Arrays.toString(array1));
// Counts and RETURN: reports how many times each number is present
int counter1 = 0;
int counter2 = 0;
int counter3 = 0;
int counter4 = 0;
int counter5 = 0;
int counter6 = 0;
for (int i = 0; i < array1.length; i++) {
if (array1[i] == 1) {
counter1++;
}
if (array1[i] == 2) {
counter2++;
}
if (array1[i] == 3) {
counter3++;
}
if (array1[i] == 4) {
counter4++;
}
if (array1[i] == 5) {
counter5++;
}
if (array1[i] == 6) {
counter6++;
}
}
System.out.println("There are " + counter1 + " ones.");
System.out.println("There are " + counter2 + " twos.");
System.out.println("There are " + counter3 + " threes.");
System.out.println("There are " + counter4 + " fours.");
System.out.println("There are " + counter5 + " fives.");
System.out.println("There are " + counter6 + " sixes.");
// Counts the longest run of the same number. A run continues only when
// consecutive numbers have the same value.
// RETURN: The repeated number and the length of the run is then printed
int counter = 1;
int runMax = 0;
int runMin = 0;
int variableNum = 0;
int startCounter = 0;
int endCounter = 0;
for (int i = 0; i < array1.length - 1; i++) {
if (array1[i] == array1[i + 1]) {
counter++;
if (counter >= runMax) {
runMax = counter;
startCounter = i - counter +2;
// runMin = i-counter+1;
variableNum = array1[i];
endCounter = i+1;
}
} else {
counter = 1;
}
}
System.out.println("The longest run is " + runMax
+ " times and the number is " + variableNum + ". ");
System.out.println("The run starts at " + startCounter
+ " and ends at " + endCounter);
for (int i = 0; i < array1.length; i++) {
if (i==startCounter) {
System.out.print("(");
}
System.out.print(array1[i]);
if (i==endCounter) {
System.out.print(")");
}
}
System.out.println();
// Prints the array with parentheses outside the longest run, if there
// is more than one max run, use the last one.
}
}
Okay. I think I have this. The first answer was close, but if you run the program a few times, you discover issues. There is a logic error somewhere in your above code, but I have a work around. I think it is how you get the endCounter. It seems to count odd. But I got the program to work as far as I can tell. Try this out. I have run it several times and it seems consistent.
import java.util.Random;
import java.util.Arrays;
/**
* Write a description of class ArrayRunner1 here.
*
* #author Ibrahim Khan
* #version (a version number or a date)
*/
public class ArrayRunner1 {
/**
* This method will generate my random numbers for my array.
* #param min minimum random value wanted
* #param max maximum random value wanted
* #return randomNum a random number between 1 and 6 inclusive
*/
public static int randInt(int min, int max) {
Random rand = new Random();
int randomNum = rand.nextInt((max - min) + 1) + min;
return randomNum;
}
public static void main(String[] args) {
System.out.println("\f");
//Part 1 - Generate a random array of length 40 with random 1-6 inclusive
int[] array1 = new int[40];
for (int i = 0; i < array1.length; i++) {
array1[i] = randInt(1, 6);
}
System.out.println(Arrays.toString(array1));
//Counts and RETURN: reports how many times each number is present
int counter1 = 0;
int counter2 = 0;
int counter3 = 0;
int counter4 = 0;
int counter5 = 0;
int counter6 = 0;
for (int i = 0; i < array1.length; i++) {
if (array1[i] == 1) {
counter1++;
}
if (array1[i] == 2) {
counter2++;
}
if (array1[i] == 3) {
counter3++;
}
if (array1[i] == 4) {
counter4++;
}
if (array1[i] == 5) {
counter5++;
}
if (array1[i] == 6) {
counter6++;
}
}
System.out.println("There are " + counter1 + " ones.");
System.out.println("There are " + counter2 + " twos.");
System.out.println("There are " + counter3 + " threes.");
System.out.println("There are " + counter4 + " fours.");
System.out.println("There are " + counter5 + " fives.");
System.out.println("There are " + counter6 + " sixes.");
//Counts the longest run of the same number. A run continues only when consecutive numbers have the same value.
//RETURN: The repeated number and the length of the run is then printed
int counter = 1;
int runMax = 1;
int runMin = 0;
int variableNum = 0;
int startCounter = 0;
int endCounter = 0;
for (int i = 0; i < array1.length - 1; i++) {
if (array1[i] == array1[i + 1]) {
counter++;
if (counter >= runMax ){
runMax = counter;
runMin = i - counter ;// was plus one I cahnged this.
variableNum = array1[i];
startCounter = i - counter + 2;
endCounter = i + counter -1;
}
} else {
counter = 1;
}
}
System.out.println("The longest run is " + runMax + " times and the number is " + variableNum + ". ");
System.out.println("The run starts at " + startCounter + " and ends at " + endCounter);
//Prints the array with parentheses outside the longest run, if there is more than one max run, use the last one.
String output = "";// added this
for(int x = 0; x < array1.length; x++)
{
if( x == startCounter)
{
output += "("+array1[x];
}
else if( x == startCounter + runMax )
{
else if( x == startCounter + runMax )
{
if(x == array1.length-1)
{
output += ")";
}
else
{
output += ")"+array1[x];
}
}
else
{
output += array1[x];
}
}
System.out.print("\n"+output);
}
}
Here's a shorter, more generic solution. This method takes any array of ints and prints parenthesis around the longest run of numbers. If there are two runs of the same lengths it prints it around the first one.
public String makeString(int[] ints) {
if (ints.length == 0) return ""; // Quit early if there's nothing to do.
// Initialize variables.
int lastNumber = ints[0];
// We keep track of the all time best run. Defaults to first int found.
int bestStart = 0;
int bestRun = 1;
// ... as well as the current run.
int currentStart = 0;
int currentRun = 1;
String s = ""+ints[0];
// Starting from the second int, we check if the current run is continuing.
for (int i = 1; i < ints.length; i++) {
int current = ints[i];
// If the current run continues, we update currentStart/currentRun, else we reset it.
if (current == lastNumber) {
currentRun++;
} else {
currentStart = i;
currentRun = 1;
}
// Now we check if the currentRun is better than the best.
// If so, we update bestStart/bestRun.
if (currentRun > bestRun) {
bestStart = currentStart;
bestRun = currentRun;
}
lastNumber = current;
s += current;
}
// Now that we've found it, we insert parenthesis aaaaaaand we're done!
return s.substring(0, bestStart)
+"("+s.substring(bestStart, bestStart+bestRun)+")"
+s.substring(bestStart+bestRun);
}
I need to calculate the sum of 2^0+2^1+2^2+...+2^n, where n is a number entered by the user. The main problem is that I don't know how to use the while loop to sum the different result of 2^n up.
Here is what I've tried:
import java.util.Scanner;
public class SumOfThePowers {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.println("Type a power: ");
int power = Integer.parseInt(reader.nextLine());
int number = 2;
int i = 0;
double sum = 0;
while(power <= i) {
Math.pow(number, i);
sum = sum + Math.pow(number, i);
i = i + 1;
}
int result = (int)Math.pow(number, i);
System.out.println("The sum is: " + result);
}
}
Only you have to do is:
import java.util.Scanner;
public class SumOfThePowers {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.println("Type a power: ");
int power = Integer.parseInt(reader.nextLine());
double sum = Math.pow(2,power+ 1 ) - 1;
System.out.println("The sum is: " + sum);
}
}
In this link explains the math expresion
All fine, just a few changes.
Change the parts code to
System.out.println("Type a power: ");
int power = Integer.parseInt(reader.nextLine());
int number = 2;
int i = 0;
double sum = 0;
/*Remove this --------> while(power <= i) {*/
while (i <= power) {//it should be this
/*Remove this -------> Math.pow(number, i);*/
sum = sum + Math.pow(number, i);
i = i + 1;
}
System.out.println("The sum is: " + sum);
Your conditional is backwards, it should read:
while (i <= power)
You compute the sum of powers, then completely ignore it, just printing out the result of 2^i. you should be printing out sum, something like:
while (i <= power) {
sum += Math.pow(number, i);
i++;
}
System.out.println("The sum is: " + sum);
For style points this won't handle a negative power, so you'll need to test for that.
Dont understand why do you want to loop in this case. You can do it like :
System.out.println("The sum is: "+(Math.pow(2, power+1)-1 ));
But if you really want to use loop try this :
Scanner reader = new Scanner(System.in);
System.out.println("Type a power: ");
int power = Integer.parseInt(reader.nextLine());
int number = 2;
int i = 0;
double sum = 0;
while(i<=power) {
sum = sum + Math.pow(number, i);
i = i + 1;
}
int result = (int)Math.pow(number, i);
System.out.println("The sum is: " + sum);
Here is a solution with comments to explain the logic. While loops need some kind of variable to control the number of iterations. That variable of course needs to be updated somewhere inside the loop.
You can compute the sum of the powers with the Math.pow() function, obviously. No import statement is needed to use it. I hope this helps. Good luck.
/* Scanner and variable to get and hold user input */
Scanner scan = new Scanner( System.in );
int userInput = 0;
/* Variable to hold the sum, initialized to 0.0 */
double sum = 0.0;
/* Prompt the user, and obtain the reply */
System.out.print( "Enter the exponent: ");
userInput = scan.nextInt();
/* The while loop and it's initialized counter */
int counter = 0;
while( counter <= userInput ){
/* Add each power to sum using Math.pow() */
sum = sum + Math.pow( 2, counter );
/* Watch the output as the loop runs */
System.out.println( "Sum: " + sum );
counter++; // Increment counter, so the loop exits properly
} // End while loop
public class SumofSquare {
public static void main(String[] args) {
// TODO Auto-generated method stub
String c = "123";
char d[] = c.toCharArray();
int a[] = new int[d.length + 1];
for (int i = 0; i < d.length; i++)
a[i] = d[i] - 48;
int r = 0;
for (int i = 0; i < c.length(); i++)
r = r + (int) Math.pow(a[i], a[i + 1]);
System.out.println(r);
}
}
import java.util.Scanner;
public class SumOfThePowers {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.println("Type a number:");
int power=Integer.parseInt(reader.nextLine());
int number=2;
int i=0;
int result=0;
while (power>=i) {
result += (int)Math.pow(number, i);
i++;
}
System.out.println("The result is "+result);
}
}
import java.util.Scanner;
public class SumOfThePowers {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.println("Type a number:");
double power=Double.parseDouble(reader.nextLine());
int number=2;
int i=0;
double sum=0;
while (power>=i) {
sum=sum+Math.pow(number, i);
i++;
}
System.out.println("The sum is "+sum);
}
I can't seem to figure out what I did wrong with my code to create an infinite loop. I would really appreciate it if someone could help explain this to me.
import java.util.Scanner;
class LoopMath1 {
public static void main(String[] args) {
Scanner inputScanner;
inputScanner = new Scanner(System.in);
//gets a number from a user and parses the string as an int
System.out.println("Please give me a positive number");
String userNum;
userNum = inputScanner.nextLine();
System.out.println("Your number is " + userNum + ".");
int number = Integer.parseInt(userNum);
printX(number); //function call
//prints 2 to the x power
System.out.print("2^" + number + "=");
int j = 1;
int twoToThe = 2;
while (j < number) {
twoToThe *= 2;
j++;
}
System.out.print(twoToThe);
//determines if the user number is prime
int i = 0;
for (i = 1; 1 < number; i++) {
int nPrime = number;
if (nPrime == 0) {
System.out.println(number + " is not prime.");
break;
} else {
System.out.println(number + " is prime.");
}
}
}
//this is a function to print a certain amount of Xs, depending on the user input
public static void printX(int nTimes) {
final int WIDTH = nTimes;
while (nTimes < WIDTH) {
System.out.print("x");
nTimes += 1;
}
}
}
for (i=1; 1 < number; i++) has a typo. 1 should be i as in for (i=1; i < number; i++)
Replace
for (i=1; 1 < number; i++) {
by
for (i=1; i < number; i++) {
Your incrementor initialized in the first part of your for loop must be tested in the second part preferably and incremented in the third one.
I'm currently working on a program designed to perform some statistical analysis. Specifically, I want it to store some random integers (say 10, between min and max inclusive) in an array, compute the min, max, mode, and a few other values through separate methods, and give the user a menu with which to either choose a method (and loop back to the menu, if they do so) or exit.
My biggest problems right now are that the main program requires two inputs to carry out any method (doesn't do anything after putting in the first), and also that each method returns 0 or 0.0.
Here is my code:
import java.util.Random;
public class Stats extends Main
{
int sampleSize;
double count;
double ave;
double sum;
int min;
int max;
int mode;
int evenCount;
int oddCount;
int countMatching;
//Constructor: use an RNG to generate sampleSize integers between minValue and maxValue. Store the numbers in an array named 'data'.
public Stats()
{
sampleSize = 10;
data = new int[sampleSize];
for (int i = 0; i < sampleSize; i++)
{
Random rand = new Random();
data[i] = rand.nextInt((max - min + 1) + min);
}
return;
}
//Method: return the sample set's max value
public int getMax()
{
max = data[0];
for(int i = 0; i < sampleSize; i++)
{
if (data[i] > max)
max = data[i];
}
return max;
}
//Method: return the min value
public int getMin()
{
min = data[0];
for(int i = 0; i < sampleSize; i++)
{
if (data[i] < min)
min = data[i];
}
return min;
}
//Method: return the average value
public double getAve()
{
count = sampleSize;
sum = 0;
for(int i = 0; i < sampleSize; i++)
{
sum = sum + data[i];
}
ave = sum / count;
return ave;
}
//Method: return the mode; in case of a tie, choose the smallest value
public int getMode()
{
int popularity1 = 0;
int popularity2 = 0;
int array_item;
for(int i = 0; i < sampleSize; i++)
{
array_item = data[i];
for(int j = 0; j < sampleSize; j++)
{
if(array_item == data[j])
popularity1++;
}
if(popularity1 >= popularity2)
{
mode = array_item;
popularity2 = popularity1;
}
}
return mode;
}
//Method: return the count of even numbers
public int getEven()
{
int evenCount = 0;
for (int i = 0; i < sampleSize; i++)
{
if (data[i] % 2 == 0)
evenCount++;
}
return evenCount;
}
//Method: return the count of odd numbers
public int getOdd()
{
int oddCount = 0;
for (int i = 0; i < sampleSize; i++)
{
if (data[i] % 2 != 0)
oddCount++;
}
return oddCount;
}
//Display all numbers, formatted in columns (hint: pg. 158)
public void displaySampleSet()
{
for (int i = 0; i < sampleSize; i++)
{
}
}
//Return the count of numbers in the sample set that match the input parameter
public int countMatching(int match)
{
int countMatching = 0;
return match;
}
//Create a list of private variable(s) that belong to the Stats class
private int[] data;
}
And here is the main program:
import java.util.*;
public class Main
{
public static void main(String[] args)
{
int input;
int stats;
Scanner keyboard = new Scanner(System.in);
Stats g = new Stats();
System.out.println("Welcome to the Stats Program!");
System.out.println();
System.out.println("Main Menu");
System.out.println();
System.out.println("1) Get max value");
System.out.println("2) Get min value");
System.out.println("3) Get the mean");
System.out.println("4) Get the mode");
System.out.println("5) Get the count of even numbers");
System.out.println("6) Get the count of odd numbers");
System.out.println("7) Display the sample set");
System.out.println("8) Return the count of numbers in the sample set that match the input parameter");
System.out.println("9) Exit");
System.out.println();
stats = keyboard.nextInt();
while (stats != 9)
{
if (stats == 1)
{
g.getMax();
input=keyboard.nextInt();
System.out.println("Max is: " + g.getMax());
}
else if (stats == 2)
{
g.getMin();
input=keyboard.nextInt();
System.out.println("Min is: " + g.getMin());
}
else if (stats == 3)
{
g.getAve();
input=keyboard.nextInt();
System.out.println("Mean is: " + g.getAve());
}
else if (stats == 4)
{
g.getMode();
input=keyboard.nextInt();
System.out.println("Mode is: " +g.getMode());
}
else if (stats == 5)
{
g.getEven();
}
else if (stats == 6)
{
g.getOdd();
}
else if (stats == 7)
{
g.displaySampleSet();
}
else if (stats == 8)
System.out.println("");
System.out.println("View other stats?");
System.out.println("");
System.out.println("1) Max 2) Min 3) Mean 4) Mode 5) Count of evens 6) Count of odds 7) Sample set numbers 8) Count of numbers that match input parameter 9) Exit");
stats = keyboard.nextInt();
}
System.out.println("Thank you for using the Stats Program. See you next time!");
}
}
Both programs are incomplete, but I'm still getting values for each method (after two inputs), loops after they execute, and the exit works as intended.
Any tips or parts that are glaringly wrong/missing? I'd really like to understand this.
Thanks in advance!
When you create a Stats, the data array is immediately initialised in the constructor using the max and min fields. But these are zero at this point (because you leave them blank, and Java initialises blank int declarations to zero). You then call your random number generator:
data[i] = rand.nextInt((max - min + 1) + min);
min and max are zero, so this evaluates to:
data[i] = rand.nextInt(1);
and Random.nextInt() returns values up to, but not including, the input (see the docs).
So your 'random' data will always be zeros; therefore the minimum, maximum and average will also be zero.
For some reason the average is being populated wrong when I pass the array to the method I get a really low percent. It almost seems like since the Array shotsMade is only recording integers for made shots and not misses it is not calculating off the right base.
import java.util.*;
public class Test {
public static void main(String[] args) {
int myGameCounter = 1;
int shotCount = 0;
int shotCount1 = 0;
int [] shotsMade = new int [5];
int sum = 0;
System.out.print("Enter Player's Free Throw Percentage: ");
Scanner input = new Scanner(System.in);
int percent = input.nextInt();
//Game #1
System.out.println("Game " + myGameCounter + ":");
Random r = new Random();
myGameCounter++;
shotCount = 0;
for (int i = 0; i < 10; ++i){
boolean in = tryFreeThrow(percent);
if (in) {
shotCount++;
System.out.print("In" + " ");
}
else {
System.out.print("Out" + " ");
}
}
System.out.println("");
System.out.println("Free throws made: " + shotCount + " out of 10");
shotsMade[0]= shotCount;
//Game #2
System.out.println("");
System.out.println("Game" + myGameCounter + ":");
myGameCounter++;
shotCount1 = 0;
for (int i = 0; i < 10; ++i){
boolean in = tryFreeThrow(percent);
if (in) {
shotCount1++;
System.out.print("In" + " ");
}
else {
System.out.print("Out" + " ");
}
}
System.out.println("");
System.out.println("Free throws made: " + shotCount1 + " out of 10");
shotsMade[1]= shotCount1;
System.out.println("");
System.out.println("Summary:");
System.out.println("Best game: " + max(shotsMade));
System.out.println("Total Free Throws Made: " + sum(shotsMade) + " " + "out of 20");
System.out.println("Average Free Throw Percentage: " + average(shotsMade) +"%");
}//main
public static boolean tryFreeThrow(int percent) {
Random r = new Random();
int number = r.nextInt(100);
if (number > percent){
return false;
}
return true;
}
public static float average(int nums[]) {
int total = 0;
for (int i=0; i<nums.length; i++) {
total = total + nums[i];
}
float f = (total / nums.length);
return (float)total /(float)nums.length;
}
public static int sum(int nums[]) {
int sum = 0;
for (int i=0; i<nums.length; ++i) {
sum += nums[i];
}
return (int)sum;
}
public static int max(int nums[]) {
int max=nums[0];
for (int i=1; i<nums.length; i++) {
if (nums[i] > max)
max = nums[i];
}
return max;
}
}//class
You are calculating the avarage of 5 numbers but you only set 2. So if all shots hit your array will look like this: 10, 10, 0, 0, 0 and the avarage will be 4.
Old issue, you are using integer arithmetic total / nums.length with returns you an int value. You later assign it to a float, but the value already has been truncated.
Just change one of the values to float before the division, v.g. ((float) total) / num
Among others, your expression
float f = (total / nums.length);
will yield an inaccurate result.
Both total and nums.length are integers, and any operation between integers always results in an integer.
Example: if total=10 and nums.length=3, you'd expect the result to be 3.333... but actually the result is just 3. Only after that do you cast it to a float, resulting in 3.0.
To get the required result, you need to cast both integers to floats before dividing:
float f = (float) total / (float) nums.length;