For my assignment I am to write a file that uses an input of trials to determine an average for a person winning a prize by opening a soda cap and looking if they won. They have a 1 in 5 chance to win. Once I have the averages for the separate trials, I am to read the trials back and calculate the average. I am having troubles trying to read the doubles from the file. This is my code so far.
import java.util.Scanner;
import java.io.File;
import java.io.PrintWriter;
import java.io.IOException;
public class BottleCapPrize
{
public static void main(String[] args) throws IOException
{
double averageBottles = 0.0;
double randNum = 0.0;
int bottleSum = 0;
int numBottles = 1;
int bottle = 0;
int maxRange = 6;
int minRange = 1;
int oneTrial = 0;
int winPrize = 1;
double token = 0;
int totalSumCaps = 0;
Scanner in = new Scanner(System.in);
//Generates bottle number for first test
randNum = Math.random();
bottle = ((int)((randNum) * (maxRange - minRange)) + minRange);
//construct an object called outFile to allow access to output methods of the PrintWriter class
PrintWriter outFile = new PrintWriter(new File("trials.txt"));
//Gets users input for how many trials
System.out.print("Enter the amount of trials: ");
int trials = in.nextInt();
System.out.println();
//Check averages for entered trials
for (int loop = 1; loop <= trials; loop++)
{
//Clears out the loops variables each time through
if(loop != 0)
{
averageBottles = 0;
bottleSum = 0;
oneTrial = 0;
numBottles = 0;
}
for(int x = 1; x <= 20; x++)
{
if(x == 20) //One trial is completed
{
averageBottles = bottleSum / x;
//Replaces the old bottle number for a new bottle
randNum = Math.random();
bottle = ((int)((randNum) * (maxRange - minRange)) + minRange);
}
else if(bottle == winPrize)
{
oneTrial = numBottles;
if(oneTrial == 0)
{
oneTrial = 1;
}
//Replaces the old bottle number for a new bottle
randNum = Math.random();
bottle = ((int)((randNum) * (maxRange - minRange)) + minRange);
}
else if(bottle != winPrize) //not a winner, gets new bottle and increments the number of bottles tested
{
//Replaces the old bottle number for a new bottle
randNum = Math.random();
bottle = ((int)((randNum) * (maxRange - minRange)) + minRange);
oneTrial = numBottles;
numBottles ++;
}
bottleSum += oneTrial; //Adds the sum from each trial
}
outFile.println("Trial " + loop + "." + " " + averageBottles); //Prints the averages to the file
System.out.println("Trial " + loop + "." + " " + averageBottles);
//outFile.println("Trial " + "=" + " " + averageBottles); //Prints the averages to the file
//System.out.println("Trial "+ "=" + " " + " " + averageBottles);
}//end of for loop
outFile.close ( );//close the file when finished
//Read the trial data back in and calculate the average
File fileName = new File("trials.txt");
Scanner inFile = new Scanner(fileName);
//read file and get data
while(inFile.hasNext())
{
token = inFile.nextDouble();
totalSumCaps += token;
}
inFile.close();
double totalAverageCaps = totalSumCaps / trials;
//Print results
System.out.println();
System.out.println("The average number of caps opened in order to win a prize is: " + totalAverageCaps);
}
}
If you're asking how to read in a String and convert it to a double, then all you need to do is use next() from Scanner, which returns a String. Then you can use Double.parseDouble(String s) to convert your String to a double. Or you could use nextDouble() from Scanner.
Not sure if you've learned exception handling yet, but if so, you can use a try-catch block to catch a possible NumberFormatException. Also, if you've learned methods, you should use them, ie you should have as little code as possible in your main. You can use methods to make your code a lot cleaner.
EDIT:
You're getting an InputMismatchException from nextDouble() because the token that you're reading is not a double.
Related
This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 1 year ago.
The output is taking count, name, income and then again income according to the number of counts and then shows outOfBound error for the count.
Here is the code -
public class Main { // Tax Calculator App
public static long calculateTax(long income1){
long tax = 0;
if (income1 >= 300000) {
tax = income1 * 20 / 100;
} else if (income1 >= 100000 && income1 < 300000) {
tax = income1 * 10 / 100;
} else if (income1 < 100000) {
tax = 0;
System.out.println("Tax Amount = 0 ");
}
return tax;
}
public static void main(String[] args) {
System.out.println("Tax Calculator App");
System.out.println("-----WELCOME-----");
Scanner sc = new Scanner(System.in);
System.out.println("Enter total person count: ");
int count = sc.nextInt();
sc.nextLine();
String[] pName = new String[count];
long[] pIncome = new long[count];
System.out.println("Enter the name: ");
for (int i = 0; i <= count; i++) {
pName[i] = sc.nextLine();
System.out.println("Enter the income: ");
}for (int i = 0; i <= count; i++) {
pIncome[i] = sc.nextLong();
sc.nextLine();
long tax = 0;
System.out.println("Name: " + pName + "Tax: " + tax);
}
}
}
You are using a <= (less than or equals) operator in your for loop. This mean it will reach the person count and attempt to index the pName array by the count.
For example, say the count is 1, the array will be initialized with a size of 1, and it'll access pName[0], then pName[1], which is out of bounds, as the size is one.
You're also referencing the entire array in the printed result, you should be indexing to get the person's name.
Revised code for you is here: https://replit.com/#viomckinney/SOHelp#Main.java (Note: Indentation is not perfect as I just did a quick copy)
As #Violet McKinney and #Henry Twist were saying, your array is out of bounds because of the =.
Also, after updating the loop I checked your output is missing the name. The outcome was a java object.
On your last part of the code:
for (int i = 0; i < count; i++) {
pIncome[i] = sc.nextLong();
sc.nextLine();
long tax = 0;
System.out.println("Name: " + pName[i] + "Tax: " + tax);
}
pName => pName[i]
First of all here is my code
import java.util.Scanner;
public class Pengulangan {
public static void main(String[] args) {
Scanner sc = new Scanner (System.in);
int i, number, line, total;
int even, b = 0;
double rat;
System.out.print("Input number: ");
number = sc.nextInt();
even = number/2;
System.out.print("Total sum of number from 1 to number " + number + " is " + even + "\n");
i = 2;
line = 1;
while (i <= number) {
System.out.println("Even number-" + line + " is " +i);
line = line+1;
i = i +2;
}
total = ((number/2) * (even+1));
System.out.printf("Total sum of even number from the number " + number + " = " + total + "\n");
rat = 2*(total/number);
System.out.printf("Sum of average number from the number " + number + " = " + rat + "\n");
}
}
On this specific line on top of the second S.O.P
even = number/2;
i would like to put a loop there to find out how many Even numbers are on the input (ex- 10)
So i tried this code
int i = 1;
while (i <= number) {
if (i%2 == 0)
even = even + 1;
else
odd = odd + 1; //Not going to use this..
i++;
}
System.out.println("Total sum of even number is : ")
I tried putting that code in but i can't make it work, i tried it myself with only the code above and the results are exactly what im looking for but i can't put that in my first code ( the top one ), so i ended up using a sneaky way to get the even numbers.
I need help putting that total sum code to my main code
Sounds like a homework. You don't need loops or anything fancy, if you just want to get the sum of even numbers up to the number you input. Let n be the input number from your program and
class Main {
public static void main(String[] args) {
int n = 10;
//This is the math forumla
int total_sum_math = (((n/2)*((n/2)+1)));
System.out.println("Total sum of even number is : "+total_sum_math+"");
}
}
Reference: https://math.stackexchange.com/questions/3285727/sum-of-even-numbers-n
Our professor gave us a list of 982 numbers in a text file and we have read text from the file and print out some info about the numbers. I have everything correct so far, (she gave us the correct answers), except the total of the odd numbers. I can't figure out how to get the average of the odd numbers which is 48201.56.
I keep getting the result 97354, which is weird because I'm following the same method I used to find the average of all the numbers and the average of the even numbers.
import java.io.*;
import java.util.*;
public class Homework1sem2
{
public static void main(String args[]) throws IOException
{
System.out.println("Student name: Ethan Creveling "
+ "\nEmail: ec904066#wcupa.edu");
double f = 0;
double e = 0;
double d = 0;
int c = 0;
int b = 0;
int a = 0;
File myFile = new File("numbers.txt");
Scanner inputFile = new Scanner(myFile);
while (inputFile.hasNext())
{
int i = inputFile.nextInt();
a++;
d += i;
if(i%2 == 0)
{
b++;
e += i;
}
else
c++;
f += i;
}
System.out.println("Total number: " + a);
System.out.println("Total even number: " + b);
System.out.println("Total odd number: " + c);
System.out.println("Total average: " + d/a);
System.out.println("Total even average: " +e/b);
System.out.println("Total odd average: " + f/c);
}
}
I would like to know why the answer for "Total odd average" isn't 48201.56. Thanks
Your else statement is only performing the c++; operation.
Wrap it in brackets like this:
else {
c++;
f += i;
}
f += i; is being performed outside of the else statement which means that it is being called on every loop of the while. If you check your values, you should find that both f and d are the same value.
If you encapsulate your else statement as follows, this should fix the problem
else {
c++;
f += i;
}
I am having trouble with a program that looks to compute the chance of someone winning a contest that they have a 1 in 5 chance of winning. It is a simulation that repeats this 1000 times. The current loop iterates once correctly but just outputs zero to the file for all other loops and I can't figure out why.
import java.util.Scanner;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.File;
public class BottleCapPrize
{
public static void main (String [ ] args) throws IOException
{
//establishing scanner and variables
Scanner in = new Scanner(System.in);
int minimumTrials = 1000;
int enteredTrials = 0;
int won = 0;
int triesToWin = 0;
double totalTries = 0;
int winningValue = 0;
//establishes the number of trials and sais if it is less than 1000
while(enteredTrials < minimumTrials)
{
System.out.println("Please enter a number of trials greater than 1000: ");
enteredTrials = in.nextInt();
if(enteredTrials >= minimumTrials)
{
System.out.println("You enetred " + enteredTrials + " trials.");
}
else
{
System.out.println("You entered an incorrect number of trials.");
}
}
//establishes file to write to
PrintWriter outFile = new PrintWriter(new File("prizeResults.txt"));
//writes to these files the amount of tries it takes to get the prize 1000 times
for (int loop = 1; loop <= enteredTrials; loop++)
{
while(won != 1)
{
winningValue = (int)((Math.random() * 5.0) + 1.0);
if(winningValue == 1)
{
won ++;
triesToWin ++;
}
else
{
triesToWin ++;
}
}
winningValue = 0;
outFile.println(triesToWin);
triesToWin = 0;
}//end of for loop
outFile.close ( ); //close the file when finished
//finds the average number of tries it took
File fileName = new File("prizeResults.txt");
Scanner inFile = new Scanner(fileName);
while (inFile.hasNextInt())
{
totalTries = totalTries + inFile.nextInt();
}
double averageTries = totalTries/enteredTrials;
//tells the user the average
System.out.println("You would have to by an average of " + averageTries + " bottles to win.");
}//end of main method
}//end of class
You are not resetting won back to zero. Thus after the first time, when you increment won to 1, the while loop ends, and then in each subsequent for loop, it skips the while loop and prints value of triesToWin which you set back to zero.
Try adding
won = 0;
after writing to the file.
So, I'm trying to create a driver for my method. I apologize in advance, I know very little about what I'm talking about. What the program does, is it calculates sine, cosine, and the exponential function by means of taylor series for a number that the user inputs. The use of Math.pow and Math.fact were not allowed. My compiler isn't giving me any errors, and I'm all out of ideas at this point. In addition, the scanner doesn't seem to stop accepting input after I press enter. It continues to take numbers, but doesn't do anything else. It gives an exception when I type a letter. High possibility of ID10T error. I know that the output isn't well formatted yet, but that's because I haven't had a chance to see it yet. If someone could help me figure this out, I would be very greatful. Thanks in advance!
-An aspiring code monkey
Driver (Lab4.java)
/*
This program is being created to solve Lab 4.
*/
import java.util.*;
public class Lab4
{
public static void main(String[] args)
{
String again, more = "y";
while (more.toUpperCase().charAt(0) == 'Y')
{
Scanner keyboard = new Scanner (System.in);
System.out.println("Input X: ");
Function number = new Function();
double x = number.x();
System.out.println("x = " + x);
Function sine = new Function();
double mySin = sine.funcSine();
Function cosine = new Function();
double myCos = cosine.funcCos();
Function expo = new Function();
double myExp = expo.funcExp();
System.out.println("\t\t\t\tLibraryResult My Result");
System.out.println("\n\t\tsin(" + Function.x() + ")" + " = " + "\t\t\t" + Math.sin(Function.x()) + "\t" + mySin);
System.out.println("\n\t\tcos(" + Function.x() + ")" + " = " + "\t\t\t" + Math.cos(Function.x()) + "\t" + myCos);
System.out.println("\n\t\texp(" + Function.x() + ")" + " = " + "\t\t\t" + Math.exp(Function.x()) + "\t" + myExp);
System.out.println("\n\t\t\tDo more (Y/N) ? ");
more = keyboard.next();
String junk = keyboard.nextLine();
}
}
}
Method (Function.java)
/*
This class provides the information for the parent to use in order to solve Lab 4.
*/
import java.util.*;
public class Function
{
Scanner keyboard = new Scanner(System.in);
public static int number;
private double temp = 1;
private double last = 1;
public static double x()
{
Scanner keyboard = new Scanner(System.in);
double x = keyboard.nextDouble();
return x;
}
public static double pow(double value, double power)
{
if(power == 0)
{
return 1;
}
double result = value;
for(int i = 0; i < power -1; i++)
{
result = result * value;
}
return result;
}
public static double getFact()
{
while (number < 0)
{
number =(number * -1);
}
double factorial = 1;
if (0 == (number % 1))
{
do
{
factorial = factorial * number;
--number;
} while (number >= 1);
}
else //Stirling's Approximation
{
double e = 2.718281828459;
double part1 = Math.sqrt(2 * 3.141592653589 * number);
double part2a = (number / e);
double part2b = (pow(part2a,number));
factorial = (part1 * part2b);
}
return factorial;
}
public static double funcSine()
{
int place = 0;
double next = x()*1;
for(number = 3; number <= 30; number = number + 2)
{
next = next + ((pow((-1),place))*((pow(x(),number))/(getFact())));
place = place + 1;
}
double mySin = next * 1;
return mySin;
}
public static double funcCos()
{
int place = 0;
double next = 1;
for(number = 2; number <= 30; number = number + 2)
{
next = next + ((pow(-1,place))*((pow(x(),number))/(getFact())));
place = place + 1;
}
double myCos = next * 1;
return myCos;
}
public static double funcExp()
{
int place = 0;
double next = 1 + x();
for(number = 1; number <= 30; number++)
{
next = next + ((pow(-1,place))*((pow(x(),number))/(getFact())));
place = place + 1;
}
double myExp = next * 1;
return myExp;
}
}
Check the syntax of your while loop:
while (more.toUpperCase().charAt(0) == 'Y')
Think about when the program will ever not satisfy this expression.
Also you have multiple Scanners all over your code. ITs not clear why you need to keep reading inout over and over again.