Print out Average in for loop - java

This is my question
get to input a positive integer representing a number of weeks, loop
continuously until the value entered is positive. For each week, enter
a value for liters and a value for kilometers. For each value, should
loop until the value entered is positive. both values is a real
number. Then output the fuel economy for that week (liters divided by
kilometers). Finally, output the average fuel economy. You must make
good use of submodules in your answer.
This is my work
import java.util.*;
public class Exam8 {
public static void main(String[] args) {
int numweek = 0;
double valkms = 0;
double vallits = 0;
double average = 0;
double result = 0;
int count = 0;
double sum = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter number of week: ");
numweek = sc.nextInt();
while (numweek < 1) {
System.out.println("Enter a positive of number week: ");
numweek = sc.nextInt();
}
while (true) {
count++;
System.out.print("Enter value of litres: : ");
vallits = sc.nextDouble();
while (vallits < 0) {
System.out.print("Positive litres: ");
vallits= sc.nextDouble();
}
System.out.print("Enter value of kilometres: : ");
valkms = sc.nextDouble();
while (valkms < 0) {
System.out.print("Positive kilometres: ");
valkms = sc.nextDouble();
}
if (vallits == 0 || valkms == 0) {
break;
}
result = vallits / valkms;
sum = result + (double)count;
System.out.println(result);
}
//average = getAverg(sum,count);
System.out.print("Average of fuel economy is: " + average);
}
public static double getAverg(double sum, int count) {
double average;
average = sum/count;
return average;
}
}
I get a problem when input value of lit and km, for example, I like to stop when to put either of a value of lit or km. Then I have another problem with outputting an average of the result (lit/km).

This code should work:
import java.util.*;
public class App {
public static void main(String[] args) {
int numweek = 0;
double valkms = 0;
double vallits = 0;
double average = 0;
double result = 0;
int count = 0;
double sum = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter number of week: ");
numweek = sc.nextInt();
while (numweek < 1) {
System.out.println("Enter a positive of number week: ");
numweek = sc.nextInt();
}
while (count < numweek) {
count++;
System.out.print("Enter value of litres: : ");
vallits = sc.nextDouble();
while (vallits < 0) {
System.out.print("Positive litres: ");
vallits= sc.nextDouble();
}
System.out.print("Enter value of kilometres: : ");
valkms = sc.nextDouble();
while (valkms < 0) {
System.out.print("Positive kilometres: ");
valkms = sc.nextDouble();
}
if (vallits == 0 || valkms == 0) {
break;
}
result = vallits / valkms;
sum += result;
System.out.println(result);
}
System.out.print("Average of fuel economy is: " + getAverg(sum, numweek));
}
public static double getAverg(double sum, double numOfWeeks) {
double average;
average = sum/numOfWeeks;
return average;
}
}
Your first error was that the condition in the while loop wasn't correct. In order for the loop to stop you need to specify proper conditions. If condition is true it will loop indefinetely or until you set break.
Your second error was that you didn't calculate the average correctly. You should have just taken the sum for every week and added it to the current sum(which is zero at the beggining), and then just divide that sum by number of weeks to get the average.
You also didn't use your getAverg function anywhere.

Related

min max in array issue

So I have a program I wrote that finds the max and min value of a five number set. It works for the most part but when I enter a set of numbers like {5,6,7,8,9} then it outputs 9 as the max, but outputs 0 for the min. Any thoughts or suggestions.
import java.util.Scanner;
public class MinMax {
public static void main (String [] args) {
#SuppressWarnings("resource")
Scanner in = new Scanner (System.in);
final int NUM_ELEMENTS = 5;
double[] userVals = new double[NUM_ELEMENTS];
int i = 0;
double max = 0.0;
double min = 0.0;
System.out.println("Enter five numbers.");
System.out.println();
while (i < NUM_ELEMENTS) {
System.out.println("Enter next number: ");
userVals[i] = in.nextDouble();
i++;
System.out.println();
}
for (i = 0; i < userVals.length; i++) {
if (userVals[i] > max) {
max = userVals[i];
}
else if (userVals[i] < min) {
min = userVals[i];
}
}
System.out.println("Max number: " + max);
System.out.println("Min number: " + min);
}
}
Default your min to a number out of range (like Double.MAX_VALUE), and max to Double.MIN_VALUE. You might also simplify your code by removing the second loop; you can perform the logic in one loop and you might use Math.max(double, double) and Math.min(double, double). Something like,
Scanner in = new Scanner(System.in);
final int NUM_ELEMENTS = 5;
double[] userVals = new double[NUM_ELEMENTS];
System.out.println("Enter five numbers.");
System.out.println();
double min = Double.POSITIVE_INFINITY;
double max = Double.NEGATIVE_INFINITY;
for (int i = 0; i < NUM_ELEMENTS; i++) {
System.out.println("Enter next number: ");
userVals[i] = in.nextDouble();
min = Math.min(min, userVals[i]);
max = Math.max(max, userVals[i]);
}
System.out.println("Max number: " + max);
System.out.println("Min number: " + min);
Intialize your min variable to non-zero max value. Means max value that you can have in your input from console.

Rainfall program not accepted in codeLab

I am working on an assignment from MyProrammingLab:
Write a RainFall class that has the following field:
• an array of doubles that stores the rainfall for each of the 12 months of
the year (where the first index corresponds with January, the second with
February, etc.)
The class should also have the following methods :
• a method that returns the total rainfall for the entire year
• a method that returns the average monthly rainfall for the year
• a method that returns the month with the most rain as a string
• a method that returns the month with the least rain as a string
Demonstrate the class in a program that takes 12 doubles from the user (take the
doubles in the order of the months of the year, the first corresponding to the
rainfall in January, etc.). Do input validation: if the user inputs a negative
number, ignore it and continue asking them for input until you have 12
nonnegative doubles .
Once the user has given you all 12 doubles , create an instance of the RainFall
class and call its methods , printing out the total rainfall, the average
monthly rainfall, the month with the most rain, and the month with the least
rain, each on a separate line.
Here is my program, which is working fine with netbeans but rejected by codeLab:
import java.text.DateFormatSymbols;
import java.util.Scanner;
public class RainFall {
final private double[] rainFall;
public RainFall(double[] arr) {
rainFall = arr;
}
public double getTotalRain() {
double total = 0;
for(int i=0;i<rainFall.length;i++)
total = total + rainFall[i];
return total;
}
public double getAverageRain() {
double average = 0;
for(int i=0;i<rainFall.length;i++)
average = average + rainFall[i];
return average/rainFall.length;
}
public String getHighestRain() {
int j=0;
for(int i=0;i<12;i++)
if(rainFall[i]>rainFall[j])
j=i;
return new DateFormatSymbols().getMonths()[j];
}
public String getLowestRain() {
int j=1;
for(int i=0;i<12;i++)
if(rainFall[i]<rainFall[j])
j=i;
return new DateFormatSymbols().getMonths()[j];
}
public static void main(String[] args) {
Scanner myScan = new Scanner(System.in);
double[] rainfallInput = new double[12];
for(int i=1;i<=12;i++) {
System.out.print("Enter rainfall for month " + i + ":");
rainfallInput[i-1]=myScan.nextDouble();
myScan.nextLine();
if(rainfallInput[i-1]<0) {
System.out.print("Enter rainfall for month " + i + :");
rainfallInput[i-1]=myScan.nextDouble();
myScan.nextLine();
}
}
RainFall rain = new RainFall(rainfallInput);
System.out.println(rain.getTotalRain());
System.out.println(rain.getAverageRain());
System.out.println(rain.getHighestRain());
System.out.println(rain.getLowestRain());
}
}
Any help would be appreciated!
Thank you in advance
I'm assuming your answer is rejected because you can eventually input a negative number at the second rainfallInput[i-1]=myScan.nextDouble();
Try with a do-while loop instead to continuously ask for a positive number.
public static void main(String[] args) {
Scanner myScan = new Scanner(System.in);
double[] rainfallInput = new double[12];
for (int i = 0; i < 12; i++) {
double input;
do {
System.out.print("Enter rainfall for month " + (i + 1) + ":");
input = myScan.nextDouble();
myScan.nextLine();
// Optionally tell why you are repeating input
/*
if (input <= 0) {
System.out.println("You must enter a positive value");
}
*/
} while (input <= 0);
rainfallInput[i] = input;
}
RainFall rain = new RainFall(rainfallInput);
System.out.println(rain.getTotalRain());
System.out.println(rain.getAverageRain());
System.out.println(rain.getHighestRain());
System.out.println(rain.getLowestRain());
}
public double getTotalRain() {
double total = 0;
for (int i = 0; i < rainFall.length; i++) {
total += rainFall[i];
}
return total;
}
public double getAverageRain() {
return getTotalRain() / (1.0 * rainFall.length);
}
public String getHighestRain() {
double max = Double.MIN_VALUE;
int maxIndex = 0;
for (int i = 0; i < rainFall.length; i++) {
double amount = rainFall[i];
if (amount > max) {
max = amount;
maxIndex = i;
}
}
return DateFormatSymbols.getInstance().getMonths()[maxIndex];
}
public String getLowestRain() {
double min = Double.MAX_VALUE;
int minIndex = 0;
for (int i = 0; i < rainFall.length; i++) {
double amount = rainFall[i];
if (amount < min) {
min = amount;
minIndex = i;
}
}
return DateFormatSymbols.getInstance().getMonths()[minIndex];
}
Get rid of myScan.nextLine(); in the for loop and code lab will accept it.

Java-Number of scores needs to be one less in answer

So here is my code:
package e7;
import java.util.Scanner;
public class Q1 {
public static void main(String[] args)
{
double[] scores = new double[10];
double sum = 0.0D;
int count = 0;
Scanner sc = new Scanner(System.in);
do {
System.out.print("Enter a new score (-1 to end): ");
scores[count] = sc.nextDouble();
if (scores[count] >= 0.0D)
sum += scores[count];
}
while (scores[(count++)] >= 0.0D);
System.out.println("The total number of scores is: " + count );
double average = sum / (count - 1);
int numOfAbove = 0;
int numOfBelow = 0;
for (int i = 0; i < count - 1; i++) {
if (scores[i] >= average)
numOfAbove++;
else
numOfBelow++;
}
System.out.printf("Average is " + "%.2f\n",average);
System.out.println("Number of scores above or equal to the average " + numOfAbove);
System.out.println("Number of scores below the average " + numOfBelow);
}
}
How do make it display the correct number of scores calculated? If I input 2 numbers and then do the -1 one to end it keeps saying 3 scores. Should only be two. How do I fix this? Thanks
System.out.println("The total number of scores is: " + count );
You probably want:
System.out.println("The total number of scores is: " + (count - 1));
You could also change your loop from a do while to a while loop as follows,
while (true) {
System.out.print("Enter a new score (-1 to end): ");
double tempDouble = sc.nextDouble();
if (tempDouble >= 0.0D)
scores[count] = tempDouble;
sum += scores[count];
count++;
else
break;
}
That way as if your double input isn't correct it would break out of the while loop when the user entered -1. You might have to tweak it a bit for your use case.

How to use Java to calculate average from input?

I need a program that should add x numbers. The numbers should come from user input so I need some sort of loop. I have gotten as far as shown below, but I'm stuck since I have no idea how to add a new number without deleting the previous?
System.out.println("How many numbers to use?");
int number = keyboard.nextInt();
for (int i = 0; i<number ; i++) {
System.out.println("whats the number");
double first = keyboard.nextDouble();
}
If all you need is the average, you don't need to keep all the numbers you get from user input. Just keep one variable that holds their sum.
define the sum variable outside the loop (initialized to 0), and add to it each number you get from user input.
int number = keyboard.nextInt();
double sum = 0;
for (int i = 0; i<number ; i++)
{
System.out.println("whats the number");
sum += keyboard.nextDouble();
}
double average = sum / number;
public class Average {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
double sum = 0;
int num;
System.out.println("enter how many num");
num = sc.nextInt();
System.out.println("please enter " + num + " numbers");
for (int i = 0; i < num; i++) {
sum += sc.nextDouble();
}
double avg = sum / num;
System.out.println("Average of " + num + " numbers is:" + avg);
}
}

while loop - sum of even numbers and its average

http://pastebin.com/w8KntkE6#
package javaapplication9;
import java.text.DecimalFormat;
import java.util.Scanner;
public class JavaApplication9 {
public static void main(String[] args) {
// TODO code application logic here
{
int sum = 0, num, count = 0;
double average;
Scanner scan = new Scanner(System.in);
System.out.print("Enter an integer (0 to quit): ");
num = scan.nextInt();
while (num >= 0) // sentinel num of 0 to terminate loop
{
if (num % 2 == 0) {
count++;
sum += num;
System.out.println("The sum so far is " + sum);
System.out.print("Enter an integer (0 to quit): ");
num = scan.nextInt();
} else if (num % 2 != 0) {
continue;
}
System.out.println();
if (count == 0) {
System.out.println("No nums were entered.");
} else {
average = (double)sum / count;
DecimalFormat fmt = new DecimalFormat("0.###");
System.out.println("The average is " + fmt.format(average));
}
}
}
}
}
The code executes and it sums even numbers. However, when a odd number enters it returns an error or it breaks. I want it ignore any odd number. What is wrong with my code?
You continue the loop on odd numbers without modifying num - looks like it should infinite loop to me.
Am I missing something, or are you missing a nextInt() when you have an odd number? Since in the if even you have num = scan.nextInt();. You don't when num is odd.
Change
else if (num % 2 != 0){
continue;
}
to
else if (num % 2 !=0){
num = scan.nextInt();
continue;
}
just before continue statement add following code. I hope it will work correctly.
System.out.print("Enter an integer (0 to quit): ");
num = scan.nextInt();
Change to:
package javaapplication9;
import java.text.DecimalFormat;
import java.util.Scanner;
public class JavaApplication9 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
{
int sum = 0, num, count = 0;
double average;
Scanner scan = new Scanner(System.in);
System.out.print("Enter an integer (0 to quit): ");
num = scan.nextInt();
while (num >= 0) // sentinel num of 0 to terminate loop
{
if (num % 2 == 0)
{
count++;
sum += num;
System.out.println("The sum so far is " + sum);
System.out.print("Enter an integer (0 to quit): ");
num = scan.nextInt();
if (count == 0) {
System.out.println("No nums were entered.");
} else {
average = (double) sum / count;
DecimalFormat fmt = new DecimalFormat("0.###");
System.out.println("The average is " + fmt.format(average));
}
}
num = scan.nextInt();
}
}
Try this. I'm not quite sure when do you want to print the average, you could move it out of the while loop if you want to print it at the end.
public static void main(String[] args) {
// TODO code application logic here
{
int sum = 0, num, count = 0;
double average;
Scanner scan = new Scanner(System.in);
System.out.print("Enter an integer (0 to quit): ");
while ((num = scan.nextInt())> 0) // sentinel num of 0 to terminate loop
{
if (num % 2 == 0){
count++;
sum += num;
System.out.println("The sum so far is " + sum);
if (count == 0) {
System.out.println("No nums were entered.");
} else {
average = (double) sum / count;
DecimalFormat fmt = new DecimalFormat("0.###");
System.out.println("The average is " + fmt.format(average));
}
}
System.out.print("Enter an integer (0 to quit): ");
}
System.out.println("end");
}
}

Categories