This is what I have:
double[] miles = new double [10];
double milesPerWeek = 26.0 / 10;
double totalMiles = 0;
double sum = 0;
double average = 0;
System.out.println("Week\tMiles");
for (int i = 0; i < miles.length; i++){
miles[i] += milesPerWeek;
totalMiles += miles[i];
System.out.printf("Week %d\t%.1f%n", i + 1, totalMiles);
}
for (int i = 0; i < miles.length; i++)
{
sum = sum + miles[i];
average = sum / miles.length;
}
System.out.printf("The total of miles run is: %.1f%n" + sum + "\n");
System.out.printf("The average of miles run is: %.1f%n" + average);
This is the problem I'm having with sum and average. I cannot seem to format the decimal places using print f without this error message:
The total of miles run is: Exception in thread "main" java.util.MissingFormatArgumentException: Format specifier '%.1f'
Can you please direct me as I need one decimal place.
You need to pass the values as arguments, not concat them:
System.out.printf("The total of miles run is: %.1f%n\n", sum);
System.out.printf("The average of miles run is: %.1f%n", average);
System.out.println("Blah %.1f\n", sum);
You know that moment where there is an Ah Ha!!! I just had it...plus signs are not to be used in formating your output...commas are!
Corrected syntax:
System.out.printf("The total of miles run is: %.1f%n", sum, "\n");
System.out.printf("The average of miles run is: %.1f%n", average);
Related
Im trying to take doubles and double arrays as parameters for my methods, but when Im calling the methods I come up with the error, "double cannot be dereferenced".
I've tried different syntaxes, such as the var.method(array[]); , var.method(array);
I've tried multiple syntaxes on my parameter sets, (double[] array), (double array[]);
public class Rainfall extends rainfallTest
{
private double total;
private double Average;
//total rainfall for the year
public double totalRain(double[] rain){
for (int index = 0; index < rain.length; index++){
total += rain[index];
}
return total;
}//end totalRain
//calculating the monthly average
public double monthlyAvg(double totalRain){
Average = totalRain / 12.0;
return Average;
}
//calculating the month with the most rain
public double mostRain(double[] rain){
double highest = rain[0];
for (int index = 1; index < rain.length; index++){
if (rain[index] > highest){
highest = rain[index];
}
}
return highest;
}
public double leastRain(double[] rain){
double lowest = rain[0];
for (int index = 1; index < rain.length; index++){
if (rain[index] < lowest){
lowest = rain[index];
}
}
return lowest;
}
}
and the testing program:
public class rainfallTest{
public static void main(String[] args){
double rain[] = {2.2, 5.2, 1.0, 10.2, 3.2, 9.2, 5.2, 0.0, 9.9, 12.2, 5.2, 2.2};
double Average;
double total;
double most;
double least;
System.out.println("Here's the rainfall for this year");
total.totalRain(rain);
Average.monthlyAvg(total);
most.mostRain(rain);
least.leastRain(rain);
System.out.println("The total rainfall for the year is: " + total +
". the monthly average of rain is: " + Average +
". The highest rain in one month: " + most +
". The lowest amount of rain in one month: " + least);
}
}
You're not calling your methods properly. First of all, you need an instance of your class:
Rainfall rainfall = new Rainfall();
Then you can call the methods on that instance, and assign the return value to your variables:
double total = rainfall.totalRain(rain);
double average = rainfall.monthlyAvg(total);
double most = rainfall.mostRain(rain);
double least = rainfall.leastRain(rain);
Also, not a huge issue, but I don't see any reason for Rainfall to extend rainfallTest.
I have an exception in my Java program. When I run this code:
ArrayList<Integer> sum = new ArrayList<Integer>();
sum.add(10);
sum.add(15);
sum.add(20);
int total = 0;
int avg;
for(int i = 0; i < sum.size(); i++)
{
total += sum.get(i);
avg = total / sum.size();
System.out.println("The Average IS:" + avg);
}
It prints each ArrayList index element then prints the average, but when I run this code:
for(int i = 0; i<sum.size(); i++)
total = total+sum.get(i);
avg = total / sum.size();
System.out.println("The Average IS:" + avg);
It prints the average, but I have not given the bracket of the for loop.
How does the code compare?
Lambda stream method in Java 8 can solve this in a easy way:
int myArray[] = { 1, 2, 3 };
Arrays.stream(myArray).average();
The brackets are use to define block of statement
By default, a loop or a condition only read one statement. A statement could be one line or a block of statement
So here is a line
total=total+sum.get(i);
and here is the block of statement
{
total += sum.get(i);
avg = total / sum.size();
System.out.println("The Average IS:" + avg);
}
NOTE : You speak about exception but also said that there is an output in both cases, so I guess your exception is not a Java Exception but just some misunderstanding in this behavior.
EDIT : You should change avg type to accept decimal values and you are going to change a bit the line, the easier is to add a static value of float to convert the value :
float avg = 1.0f * total / sum.size();
Because there is a float here (1.0f), the result will be a float, if you only use integers, the result will be rounded in integer (even if you store it in a float).
From your question, I guess that you are learning Java.
If you are in Java 8, you might use Stream (see link for a better explanation):
The new Stream API allows to transform (map), filter values, etc.
It allows to collect them (see Collectors), regrouping them by key (groupingBy), and in your case to compute a summary statistics.
The example below shows you how to do that using either an IntStream (a Stream tailored for int) or a standard Stream:
IntSummaryStatistics stats = Arrays.asList(10, 15, 20)
.stream()
.mapToInt(Integer::intValue)
.summaryStatistics()
;
// alternative
// IntSummaryStatistics stats2 = Arrays.asList(10, 15, 20)
// .stream()
// .collect(Collectors.summarizingInt(Integer::intValue))
// ;
System.out.println("average: " + stats.getAverage());
System.out.println("count: " + stats.getCount());
System.out.println("sum: " + stats.getSum());
See the javadoc for Collectors.summarizingInt.
In java curly braces are used to group the line of code. In first block of code
ArrayList<Integer> sum = new ArrayList<Integer>();
sum.add(10);
sum.add(15);
sum.add(20);
int total = 0;
int avg;
for(int i = 0; i < sum.size(); i++)
{
total += sum.get(i);
avg = total / sum.size();
System.out.println("The Average IS:" + avg);
}
in this code you are adding element to total and same time you are calculating average. Let us see each iteration
iteration 1:
total = 10
avg = 10/3 = 3
iteration 2:
total = 25
avg = 25/3 = 8
iteration 3:
total = 45
avg = 45/3 = 15
But in case of second code block
for(int i = 0; i<sum.size(); i++)
total = total+sum.get(i);
avg = total / sum.size();
System.out.println("The Average IS:" + avg);
here code is equivalent to
for(int i = 0; i<sum.size(); i++){
total = total+sum.get(i);
}
avg = total / sum.size();
System.out.println("The Average IS:" + avg);
so in for loop, it calculates total only as
iteration 1: total = 10
iteration 2: total = 15
iteration 2: total = 45
after completion of block value of total is 45
and after block, actual average is calculated as:
avg = 45/3 = 15
In java if we don't provide curly braces to group block of code inside for, if and while by default considered only single line inside the block and execute it repeatedly based on condition.
Exception is according to you Is not achieving the expected behaviour for an average on the elements of the collections.
So, as the earlier answer it boiles down to the Java syntax for working with the Loops/conditions/statements that how we use the { // code
}
By defaults a single line of code statement followed after Loops/conditions does not need to wrap in the braces {}
Here the first snippet uses a block of statement to derive average on each element by collecting it in total and dividing with size of collection.
Whereas, the second snippet does the collection of total for all element at first and then go for finding average.
You need to account for the data precisions when deriving mathematical values like avg and use the appropriate primitive data type.
If you remove the braces, the for loop header refers to the (one) very next statement, so the following two examples are equal:
for(int i=0; i<sum.size(); i++)
total=total+sum.get(i);
avg=total/sum.size();
System.out.println("The Average IS:" + avg);
for(int i=0; i<sum.size(); i++) {
total=total+sum.get(i);
}
avg=total/sum.size();
System.out.println("The Average IS:" + avg);
When you leave the brackets for the loop away, then just the first following line will be part of the loop. That means:
for(int i=0; i<sum.size(); i++)
total=total+sum.get(i);
avg=total/sum.size();
System.out.println("The Average IS:" + avg);
Is equivalent to
for(int i=0; i<sum.size(); i++){
total=total+sum.get(i);
}
avg=total/sum.size();
System.out.println("The Average IS:" + avg);
Same counts also for e.g. if/else.
1st
for(int i = 0; i < sum.size(); i++)
{
total += sum.get(i);
}
2nd
for(int i = 0; i < sum.size(); i++)
total += sum.get(i);
//but in this for loop it considers only one statement as inside for loop
3rd
for(int i = 0; i < sum.size(); i++)
total += sum.get(i);//only this statement is considered as inside the loop
System.out.println("hello");//this statements is not considered inside the loop
1st and 2nd for loops are same
You need to insert bracket in 2nd code of for loop the following.
for(int i = 0; i<sum.size(); i++) {
total = total+sum.get(i);
avg = total / sum.size();
System.out.println("The Average IS:" + avg);
}
Because if you don't insert bracket in for loop, only one line under the for loop will execute for looping process. So you need to make bracket for starting line to ending line that you want to execute in looping process.
This code seems to run well, but am getting error message regarding calculating the sum of the integers entered.
The point of the exercise is to input a series of numbers, and after the value -1 is entered, calculate the sum of the numbers, how many numbers were entered, the mean value, and the number of odd and even numbers.
The output I get suggests the program is running fine, but still get an eror message.
With input 1 17 2 18 17 -1 should print "sum: 55" expected:<55> but was: <0>
Apologies in advance if my Java syntax is a bit inelegant. I'm fairly new at this! Code below.
import java.util.Scanner;
public class LoopsEndingRemembering {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.print("Type numbers: ");
int n;
double sum = 0.0;
int i = 0;
double average = 0.0;
int odd = 0;
int even = 0;
while (true) {
n = Integer.parseInt(reader.nextLine());
if (n != -1) {
System.out.print("Type numbers: ");
sum += n;
i++;
average = sum / i;
if (n % 2 == 0) {
even++;
} else {
odd++;
}
} else {
System.out.println("Thank you and see you later!");
System.out.println("The sum is " + sum);
System.out.println("How many numbers: " + i);
System.out.println("Average: " + average);
System.out.println("Even numbers: " + even);
System.out.println("Odd numbers: " + odd);
break;
}
}
}
}
You're printing 55.0. It seems you're getting this program tested by another program which you don't have access to the source code of.
Issue 1
You probably want to print 55 specifically.
Instead of:
double sum = 0.0;
Do:
int sum = 0;
Issue 2
Use int over double. Cast to double for the average value.
Then instead of this:
average = sum / i;
Do something like:
average = (double)sum / i;
Issue 3
Also, it seems the error message wants you to print as sum: 55.
So change this:
System.out.println("The sum is " + sum);
To:
System.out.println("sum: " + sum);
I'm trying to get the overall average of the grades. I was able to get the average of each individual grade. Now just to get the total I'm not sure how to get it.
My output is:
Quizzes:66.0
Labs:88.0
Lab_atendance: 81.0
Midterms:91.0
public static double average(int[] scoreArray, int numScores,
int maxGrade, String name) {
double sum = 0;
for (int i = 0; i < scoreArray.length; i++) {
sum += scoreArray[i];
}
double average = Math.round((sum / numScores)*100/maxGrade);
System.out.println( name + ":" + average+" %");
return average;
}
What you are doing in not average exactly! but still..
Do the same procedure for Quizzes, Labs, Lab_attendance and Midterms! Isn't it obvious?
Here your numScores will be 4!
So from your given input
Avg = ((66.0 + 88.0 + 81.0 + 91.0) / 4) * 100 / maxGrade)
Your average calculation (and method signature) seem incorrect (averages are not calculated by dividing a "max"), I would use something like
// Note the new method signature - name then a variable number of scores.
public static double average(String name, int... scores) {
double sum = 0;
for (int score : scores) { // <-- for each loop.
sum += score;
}
final double average = (scores != null) ? sum / scores.length : 0;
System.out.println(name + ":"
+ Math.round(average * 100) + " %"); //<-- Display as a percentage
return average;
}
I am writing a program where I must ask the user how many assignments they have. Then, I must ask them for their score and the maximum points possible for the assignment. I know how to find the sum of the first set of numbers they entered (their scores) but I am stuck on how I would go about totaling the maximum points possible. Here is what I have so far:
int totalNumber = scan.nextInt();
double sum = 0.0;
for (int i = 1; i <= totalNumber; i++) {
System.out.print("Assignment " + i + " score and max? ");
double score = scan.nextDouble();
double maxScore = scan.nextDouble();
sum += score;
The output looks something like this:
Assignment 1 score and max? 16 17
Assignment 2 score and max? 18 19
I am not sure how I would total the maximum points (17 and 19 in the example) because I must print the total points:
(sum of scores)/(sum of maximum points).
Thanks.
the simple answer is to add another variable for summing the maxScore
int totalNumber = scan.nextInt();
double sum = 0.0;
double maxSum = 0.0;
for (int i = 1; i <= totalNumber; i++) {
System.out.print("Assignment " + i + " score and max? ");
double score = scan.nextDouble();
double maxScore = scan.nextDouble();
sum += score;
maxSum += maxScore;
}