This loop is producing the average values of hours and amount paid, but the output is mathematically incorrect. How can I edit this code to produce the correct average hours value and average paid values?
Scanner openFile = new Scanner(inFile);
while (openFile.hasNext()) {
if (openFile.hasNextDouble()) {
totalHours += openFile.nextDouble();
numOfHourInputs++;
}
if (openFile.hasNextDouble()) {
totalPaid += openFile.nextDouble();
numOfCharges++;
}
else {
openFile.next(); }
}
averageHours = (totalHours/numOfHourInputs);
averagePaid = (totalPaid/numOfCharges);
Below is my file:
The first column is unimportant for calculating the averages. The second column contains the numbers of hours. The third column contains the charges.
This file can have more data added to it by the user - the values inside of the file can be changed.
a 10.0 9.95
b 10.0 13.95
b 20.0 13.95
c 50.0 19.95
c 30.0 19.95
Remove the else:
else {
openFile.next(); //this consumes all input
}
The following code
Double[][] values = {{10.0, 9.95},
{10.0, 13.95},
{20.0, 13.95},
{50.0, 19.95},
{30.0, 19.95}};
Double totalHours = 0.;
int numOfHourInputs = 0;
Double totalPaid = 0.;
int numOfCharges = 0;
for (final Double[] value : values) {
totalHours += value[0];
numOfHourInputs++;
totalPaid += value[1];
numOfCharges++;
}
final double averageHours = (totalHours / numOfHourInputs);
System.out.println("averageHours = " + averageHours);
final double averagePaid = (totalPaid / numOfCharges);
System.out.println("averagePaid = " + averagePaid);
produced the result
averageHours = 24.0
averagePaid = 15.55
so that it's clearly not a mathematical problem. Check your input code especially for the line
openFile.next();
You still need to skip the first token but in the right spot:
public static void main(String[] args)
{
double totalHours = 0.0;
int numOfHourInputs = 0;
double totalPaid = 0.0;
int numOfCharges = 0;
Scanner openFile = null;
try
{
openFile = new Scanner(new File("c:\\temp\\pay.txt"));
}
catch (Exception e)
{
throw new RuntimeException("FNF");
}
try
{
while (openFile.hasNext())
{
// skip the first token
String token = openFile.next();
if (openFile.hasNextDouble())
{
totalHours += openFile.nextDouble();
numOfHourInputs++;
}
if (openFile.hasNextDouble())
{
totalPaid += openFile.nextDouble();
numOfCharges++;
}
}
}
finally
{
openFile.close();
}
double averageHours = (totalHours/numOfHourInputs);
double averagePaid = (totalPaid/numOfCharges);
System.out.println("Total hours: " + totalHours);
System.out.println("Num hours input: " + numOfHourInputs);
System.out.println("----------------------------------------");
System.out.println("Average hours: " + averageHours);
System.out.println("");
System.out.println("Total payments: " + totalPaid);
System.out.println("Num payments input: " + numOfCharges);
System.out.println("----------------------------------------");
System.out.println("Average paid: " + averagePaid);
}
Here is the output that I get:
Total hours: 120.0
Num hours input: 5
----------------------------------------
Average hours: 24.0
Total payments: 77.75
Num payments input: 5
----------------------------------------
Average paid: 15.55
Related
I've encountered the problem where if I increment the for-loop my program crashes after the for-loop has been executed, but if I don't increment the for-loop and use a return statement to return projectedSales my program continues to run.
However, if I don't increase then projectedSales just outputs the last number for projectedSales1 without adding it to projectedSales.
So my question here is, how can i increment the for-loop so that projectedSales = projectedSales + projectedSales1 continues to collect data and returns projectedSales at the end?
Scanner input = new Scanner(System.in);
double projectedRevenue2025 = 0;
double projectedSales1 = 0;
double projectedSales = 0;
double baseSales;
double growthRate;
double numberOfYears;
int [] productPrice = {1825, 670, 880, 1910, 485};
DecimalFormat df = new DecimalFormat("#");
for (double i = 0; i <= 4;) {
System.out.println("What is the base sale?");
baseSales = input.nextDouble();
System.out.println("What is the growth rate?");
growthRate = input.nextDouble();
System.out.println("What is the expected number of years?");
numberOfYears = input.nextDouble();
//calculates the projected sales of the upcoming years
projectedSales1 = baseSales * (Math.pow((1 + (growthRate / 100)), numberOfYears));
System.out.println("The projected sale is: " + df.format(projectedSales1));
//this should store data from projectedSales1 into projectedSales and add it to the previous data
projectedSales = projectedSales + projectedSales1;
projectedRevenue2025 = (projectedSales1 * productPrice[(int) i]) + projectedRevenue2025;
System.out.println("The total projected revenue is: $" + df.format(projectedRevenue2025)); //prints total projected revenue
return projectedSales;
} //close for-loop
input.close();
return projectedSales;
} //closes projSales
PS. the return statement after input.close() is to return projectedSales to the main method
EDIT: I was supposed to hard code this program. My issue was with the input statements in the beginning of the loop. Thank you all, I really appreciate y'all taking the time to help.
I recommend you to use for-loop like this in your case:
for (int i = 0; i < 5; i++) {
// Do your input and previous calculations
projectedRevenue2025 = (projectedSales1 * productPrice[i]) + projectedRevenue2025;
}
I also recommend you to avoid naming variables like var, var1, var2, var2025
Try adding i++ code is like this
for (double i = 0; i <= 4; i++) {
//code goes here
}
if you take out the return statement in the loop and increment the for loop then it should collect data every time and then at the end return the sum of all of the data
Scanner input = new Scanner(System.in);
double projectedRevenue2025 = 0;
double projectedSales1 = 0;
double projectedSales = 0;
double baseSales;
double growthRate;
double numberOfYears;
int [] productPrice = {1825, 670, 880, 1910, 485};
DecimalFormat df = new DecimalFormat("#");
for (double i = 0; i <= 4; i++) {
System.out.println("What is the base sale?");
baseSales = input.nextDouble();
System.out.println("What is the growth rate?");
growthRate = input.nextDouble();
System.out.println("What is the expected number of years?");
numberOfYears = input.nextDouble();
//calculates the projected sales of the upcoming years
projectedSales1 = baseSales * (Math.pow((1 + (growthRate / 100)), numberOfYears));
System.out.println("The projected sale is: " + df.format(projectedSales1));
//this should store data from projectedSales1 into projectedSales and add it to the previous data
projectedSales = projectedSales + projectedSales1;
projectedRevenue2025 = (projectedSales1 * productPrice[(int) i]) + projectedRevenue2025;
System.out.println("The total projected revenue is: $" + df.format(projectedRevenue2025)); //prints total projected revenue
} //close for-loop
input.close();
return projectedSales;
} //closes projSales
This question already has answers here:
Best way to Format a Double value to 2 Decimal places [duplicate]
(2 answers)
Closed 5 years ago.
I am supposed to find the average of a bunch of given numbers after adding all of them up then dividing by the number of numbers given to me and the average must have 3 decimal numbers so for instead of 45.0 it would be 45.000 and mine works but only if the last number is not 0.
import java.util.Scanner;
import static java.lang.System.*;
public class Average
{
private String line;
private double average, sum, count;
public Average()
{
setLine("");
}
public Average(String s)
{
setLine(s);
}
public void setLine(String s)
{
line = s;
sum = 0.0;
count = 0.0;
average = 0.0;
}
public double getCount()
{
int num = 0;
while(num<line.length())
{
if(line.charAt(num) == 32)
{
count ++;
num ++;
}
else
num ++;
}
count ++;
return count;
}
public double getSum()
{
Scanner bobby = new Scanner(line);
while(bobby.hasNextInt())
sum = sum + bobby.nextInt();
return sum;
}
public double getAverage()
{
average = getSum()/getCount();
average = average*1000;
if(average%10>4)
{
average = Math.floor(average);
average ++;
average = average/1000.0;
}
else
{
average = Math.floor(average);
average = average/1000.0;
}
return average;
}
public String getLine()
{
return line;
}
public String toString()
{
return "";
}
}
This is my runner file
import java.util.Scanner;
import static java.lang.System.*;
public class AverageRunner
{
public static void main( String args[] )
{
String s = "9 10 5 20";
Average bob = new Average(s);
System.out.println("Find the average of the following numbers :: "+s);
System.out.println("Average = " + " " + bob.getAverage());
System.out.println();
s = "11 22 33 44 55 66 77";
Average bob1 = new Average(s);
System.out.println("Find the average of the following numbers :: "+s);
System.out.println("Average = " + " " + bob1.getAverage());
System.out.println();
s = "48 52 29 100 50 29";
Average bob2 = new Average(s);
System.out.println("Find the average of the following numbers :: "+s);
System.out.println("Average = " + " " + bob2.getAverage());
System.out.println();
s = "0";
Average bob3 = new Average(s);
System.out.println("Find the average of the following numbers :: "+s);
System.out.println("Average = " + " " + bob3.getAverage());
System.out.println();
s = "100 90 95 98 100 97";
Average bob4 = new Average(s);
System.out.println("Find the average of the following numbers :: "+s);
System.out.println("Average = " + " " + bob4.getAverage());
}
}
Use DecimalFormat:
DecimalFormat df = new DecimalFormat("#.000");
System.out.println("Nummber: " + df.format(1.2345));
When I run this code and input the double value for the first variable i.e
miles It shows an error on the read.nextDouble() line as Exception in thread "main" java.util.InputMismatchException.
/**
* Created by Ranjan Yadav on 1.10.2016.
*/
public class GasMileage {
public static void main(String[] args){
java.util.Scanner read = new java.util.Scanner(System.in);
int counter = 0;
System.out.println("Miles Driven(press 1 to quit): ");
double miles = read.nextDouble();
double totalGalon = 0;
double totalMiles = 0;
double milesPerGalon = 0;
double totalMilesPerGalon = 0;
totalMiles += miles;
while(miles != 1){
System.out.println("Gallon used: ");
double galon = read.nextDouble();
counter++;
milesPerGalon = miles / galon;
totalMilesPerGalon += milesPerGalon;
System.out.println("Miles per gallon: " + milesPerGalon);
System.out.println("Miles Driven(press 1 to quit); ");
miles = read.nextDouble();
totalGalon += galon;
totalMiles += miles;
}
if(counter == 0 ){
System.out.println("No values were entered.\nThanks for Using!\n\n");
}else{
double avg = totalMilesPerGalon / counter;
System.out.printf("Total miles driven: %.2f" , totalMiles);
System.out.printf("Total gallons used: %.2f" , totalGalon);
System.out.printf("Miles per gallon for all trips: %.2f" , totalMilesPerGalon);
}
}
}
From the Javadoc:
Throws:
InputMismatchException - if the next token does not match the Float regular expression, or is out of range
Basically, you're inputting something that is not a number.
Need to set a maximum (100) and minimum (0), for this average test result program. I understand that i would need to use '<' and'>' somewhere within my work however i am not sure how/where
import java.util.Scanner;
public class ExamResults {
public static void main(String args[]) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the 5 exam results");
double ExamResult1 = 0.0;
ExamResult1 = Double.parseDouble(keyboard.nextLine());
double ExamResult2 = 0.0;
ExamResult2 = Double.parseDouble(keyboard.nextLine());
double ExamResult3 = 0.0;
ExamResult3 = Double.parseDouble(keyboard.nextLine());
double ExamResult4 = 0.0;
ExamResult4 = Double.parseDouble(keyboard.nextLine());
double ExamResult5 = 0.0;
ExamResult5 = Double.parseDouble(keyboard.nextLine());
double averageScore;
averageScore = ((ExamResult1 + ExamResult2 + ExamResult3 + ExamResult4 + ExamResult5)/5);
System.out.println("The average Score is" + averageScore);
}
}
Try something like:
double min = Math.min(Math.min(ExamResult1, ExamResult2), ExamResult3);//similarly for others
double max = Math.max(Math.max(ExamResult1, ExamResult2), ExamResult3);//similarly for others
I would do this:
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the 5 exam results");
double[] examResults = new double[5];
double total = 0.0;
for (int i = 0; i < examResults.length; i++)
{
double value = Double.parseDouble(keyboard.nextLine());
while (value < 0 || value > 100)
{
System.out.println("Invalid score, try again");
value = Double.parseDouble(keyboard.nextLine());
}
examResults[i] = value;
total += value;
}
double averageScore;
averageScore = total / examResults.length;
System.out.println("The average Score is" + averageScore);
It is attempt to solve second task from Code Jam 2014. Unfortunately, I have an InputMisMatchException? I think problem is that first number is not double.
How I should to read such information? Link to task.
Input:
4
30.0 1.0 2.0
30.0 2.0 100.0
30.50000 3.14159 1999.19990
500.0 4.0 2000.0
My Java code:
public class CookieClickerAlpha {
public static void main(String[] args) throws FileNotFoundException {
Scanner sc = new Scanner(System.in);
PrintWriter pw = new PrintWriter(System.out);
int n = (int) sc.nextDouble();
double priceForFarm, plusCookies, goal;
double currentTime = 0.0, timeWithFarm,
timeWithoutFarm, timeForFarm, resultTime;
double currCookies = 0.0, cookiesPerSec = 2.0;
for (int i = 0; i < n; i++) {
priceForFarm = sc.nextDouble();
plusCookies = sc.nextDouble();
goal = sc.nextDouble();
while (currCookies < goal) {
timeForFarm = (priceForFarm - currCookies) / cookiesPerSec;
timeWithFarm = timeForFarm +
goal / (cookiesPerSec + plusCookies);
timeWithoutFarm = (goal - currCookies) / cookiesPerSec;
if (timeWithFarm < timeWithoutFarm) {
currCookies = 0.0;
cookiesPerSec += plusCookies;
currentTime += timeForFarm;
}
else {
currentTime += goal / cookiesPerSec;
currCookies = goal;
}
}
pw.print("Case #" + (i + 1) + ": ");
pw.println(currentTime);
}
sc.close();
pw.close();
}
}
use sc.hasNextDouble() / hasNextInt() to check whether the nxt number is a double / int and then use nextInt(), nextDouble() based on what hasNextXXX returns.
EDIT :
To read integer first , do :
if(sc.hasNextInt()){
n=sc.nextInt();
}