How to take the sum of elements from a for loop? - java

import java.util.Scanner;
class objectDetails {
double w, t, res, amt;
String ob;
void getDetails(int n) {
Scanner get = new Scanner(System.in);
int limit = n;
System.out.println("Enter Object Details\n");
for (int i = 0; i < limit; i++) {
System.out.println("Name of appliance:\n");
ob = get.next();
System.out.println("Enter the amount of watts per hour:\n");
w = get.nextDouble();
System.out.println("Enter the amount of time in hours used:\n");
t = get.nextDouble();
res = (w * t) / 1000;
amt = (res * 4.2);
System.out.println("The amount in ruppes payable=" + amt);
}
}
}
i want the sum of amt from all the iterations in the loop. Add all the amt and display the total amount payable. im new to coding trying to self learn. thank you

Before the loop,
double total = 0;
and then in the loop (after you calculate the amount)
total += amt;
and finally after the loop, something like
System.out.printf("The total is %.2f%n", total);

Assign one global variable and store the value in that variable and at last print the value of that global variable.
thats all

Related

control statement throwing arithmetic exception

this was supposed to be fairly simple, but apparently somethings wrong with my control boolean, when I input a negative number instead of ending the loop it throws an exception, any help is appreciated.
import java.util.*;
public class AverageMinMax {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
double average;
int count = 0, sum = 0, next;
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
boolean areMore = true;
System.out.println("Please enter the numbers you wish to evaluate:");
System.out.println("Followed by a negative number");
// not sure why i used a do while loop but it works i guess
do {
next = keyboard.nextInt();
sum = sum + next;
next++;
if (next < 0)
areMore = false;
} while (areMore == true);
{
sum = sum + next;
average = sum / count;
{// the minmum and max values
if (next > max)
max = next;
if (next < min)
min = next;
}
System.out.println("Your average is: " + average);
System.out.println("Your maximum number is: " + max);
System.out.println("Your minimum number is: " + min);
}
}
}
Error:
Exception in thread "main" java.lang.ArithmeticException: / by zero
at com.test.task.AverageMinMax.main(AverageMinMax.java:29)
Your issues:
You increase next instead of count.
Outsider (sum = sum + next) is also wrong. You should not add next after loop breaks.
Min-max should be calculated inside the loop.
Some improvement suggestions:
Use while it is cleaner than do-while.
Use hasNextInt to check if it is a number or not.
If your input is a char or any special character while loop breaks.
import java.util.*;
public class AverageMinMax {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
double sum = 0, average =0;
int count = 0, next = 0;
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
System.out.println("Please enter the numbers you wish to evaluate:");
System.out.println("Followed by a char or any special character to calculate and exit");
// use while it is more cleaner.
// use hasNextInt to check if it is number or not
// if your input is a char or any special character while loop breaks
while (keyboard.hasNextInt()) {
next = keyboard.nextInt();
sum = sum + next;
// the minmum and max values
if (next > max)
max = next;
if (next < min)
min = next;
count++;
}
average = sum / count;
System.out.println("Your average is: " + average);
System.out.println("Your maximum number is: " + max);
System.out.println("Your minimum number is: " + min);
}
}
Issues
count is not incremented and its causes divide by 0 error
computation of max, min, sum, average seems incorrect
solution
Repeated read input(integer) from user
if the input is positive, add to sum, update min, update max and update count
if its negative, break the input loop
if any input is passed, then compute average
if no input is passed, then do not compute average
import java.util.Scanner;
class AverageMinMax {
public static void main(String[] args) {
final Scanner keyboard = new Scanner(System.in);
int count = 0, sum = 0, min = Integer.MAX_VALUE, max = Integer.MIN_VALUE;
System.out.println("Please enter the numbers you wish to evaluate.");
System.out.println("Followed by a negative number to stop input");
do {
final int next = keyboard.nextInt();
if (next < 0) {
break;
}
sum = sum + next;
max = Math.max(max, next);
min = Math.min(min, next);
count++;
} while (true);
if (count > 0) {
double average = (sum * 1.0) / count; // need to multiply by 1.0 to have fraction
System.out.println("Your average is: " + average);
System.out.println("Your maximum number is: " + max);
System.out.println("Your minimum number is: " + min);
} else {
System.out.print("No input to process");
}
}
}
You are getting ArithmeticException because you initialize count to 0. But after that when you are getting input from console. instead of increasing the count and doing count++. You are doing next++ in the loop.
And also getting the min max should also needs to be done in loop currently they are just in block. Although they are not responsible for your error of divide by zero.
this line is
average = sum / count;

How to do an array in a loop

I am making an investment calculator.
So I will be doing a math problem and I want to loop it through each array and there will be 12 of them.
So let's say I am going to invest $1000 with a rate return of 4.5%.
So I will need to do 1000 * 0.045 + 1000 = 1,045 that equals one month. Then I need to do 1,045 * 0.045 + 1,045 = 1,092 that would equal the second month and how would I have it go through a loop like that?
Would I use a for loop? or?
This is what I have so far maybe you'll get it better by reading it. But I still need to create a loop that would like the example I gave above.
public class SimpleInvestment {
static Scanner input = new Scanner(System.in);
public static void main(String[] args)
{
double [] num = new double [11];
printWelcome();
double investTotal = getInvestAmount();
double rateTotal = getRate();
}
public static void printWelcome()
{
System.out.println("Welcome to the Investment Calulator");
}
public static double getInvestAmount()
{
double amountInvest;
System.out.print("Hou much will you be investing? ");
amountInvest = input.nextDouble();
while (amountInvest <= 0)
{
System.out.println("Amount must be greater than 0. Try again.");
System.out.print("How much will you be investing? ");
amountInvest = input.nextDouble();
}
return amountInvest;
}
public static double getRate()
{
double rate;
System.out.print("What will be the rate of return?");
rate = input.nextDouble();
while (rate < 0 )
{
System.out.println("Rate must be greater than 0. Try again.");
System.out.print("What will be the rate of return?");
rate = input.nextDouble();
}
return rate;
}
public static void calculateInterst( double num[], double investTotal, double rateTotal)
{
double total;
rateTotal = rateTotal / 100;
total = investTotal * rateTotal + investTotal;
}
}
You can use a while or for loop. In this example I used a for loop.
There is documentation in the code to walk you through the logic.
public static void calculateInterest(double num, double investTotal, double rateTotal) {
double total; //keep the total outside loop
rateTotal = rateTotal / 100; //your percent to decimal calculation
total = investTotal * rateTotal + investTotal; //intial calculation
for (int i = 1; i < num; i++) {//for loop starting at 1 because we alreay calculated the first
total += (total * rateTotal);//just calculate the rate of change
}
System.out.println(total);//either output it or return it. Whatever you want to do from here.
}
I hope this helps!
You can use below code:
where months is the investment duration in months,
investment is the amount that is being invested,
rate is the interest rate. e.g. 0.045
public static double calculateTotal(int months, double investment, double rate) {
double total = investment;
for (int i=1; i <= months; i++) {
total = total + (total * rate);
}
return total;
}

While loops being ignored

I'm trying to write a simple program which will take a number of inputs from the user and produce the max number (Highest number) min number (Lowest Number) and the average.
So far I have written the code but found that the second and third while loops were being ignored. I tested this by outputting println's. I'm new to Java but any help is appreciated :)
public void analyseInput() {
UI.clearText();
UI.print("input (end with 'done')");
double sum = 0;
double i=0;
for( i=0; UI.hasNextDouble(); i++){ //average
double amt = UI.nextDouble();
sum = (sum + amt);
}
UI.println("test0");
int maxAge = 0;
while(UI.hasNextDouble()){ //max
int age = UI.nextInt();
while(age>maxAge){
maxAge = age;
UI.println(maxAge);
}
}
double minAge = 0;
while(UI.hasNextDouble()){ //min
double age = UI.nextDouble();
if(age<minAge){
minAge = age;
}
}
double average = sum/i;
UI.nextLine(); // to clear out the input
UI.println(average);
UI.println(minAge);
}
Take out your for loop.
using it empties ui.doubles.
furthermore instead of iterating through your stack twice you might as well do the max, min and average calculations in one loop. also your max and finder isn't right, because it would only work on a sorted list and if the list was already sorted you would just look at either end of it.
If you need the min age, max age, average for a set of data, instead of parsing over it a bunch of time, you can simply do it in one go.
public void analyseInput() {
UI.clearText();
UI.print("input (end with 'done')");
double sum = 0;
double i=0;
double maxAge = Double.MIN_VALUE, minAge = Double.MAX_VALUE;
for( i=0; UI.hasNextDouble(); i++){ //average
double amt = UI.nextDouble();
sum = (sum + amt);
maxAge = Math.max(amt, maxAge);
minAge = Math.min(amt, minAge);
}
double average = sum/i;
UI.nextLine(); // to clear out the input
UI.println(average);
UI.println(minAge);
}
You must to do all operations (max, min, avg) inside a single while-loop and initialize your variable right. To each new double value, update the min and max variable. Add to an accumulator all the values and calculate the average after the loop.

Dividing values from one array by values from a separate array

I am trying to take values from separate arrays and perform divisional math. I have created a method to perform the division, but I keep getting the "bad operand..." error. I have searched and searched, but cannot find resolution. I need to be able to take the values from tripMiles and divide that by the values from gallons.
import java.util.Scanner;
public class Week6Challenge {
public static void main(String[] args) {
Scanner scan = new Scanner (System.in);
int count = 0;
//double miles = 0, gallons = 0;
//Arrays
String[] tripName;
tripName = new String[11];
double[] tripMiles;
tripMiles = new double[11];
double[] tripMPG;
tripMPG = new double [11];
double[] gallons;
gallons = new double [11];
//double miles = 0, gallons = 0;
while (count <= 9){//start while
System.out.println("Enter a description of this trip");
tripName[count] = scan.next();
System.out.println("How many miles did you drive?");
tripMiles[count] = scan.nextDouble();
System.out.println("How many gallons of gas did you use on this trip");
gallons[count] = scan.nextDouble();
count++;
}//end while
tripMPG[count] = answer(tripMiles, gallons);
System.out.println("Trip Name \t Miles Traveled \t MPG");
int k = 0;
for(k = 0; k < 10; k++){
System.out.println(tripName[k]+ "\t\t" + tripMiles[k] + "\t\t\t" + tripMPG[k]);
}
}
public static double answer(double[] num1, double[] num2){
return (num1/num2);
}
}
You are trying to divide two arrays like:
return (num1/num2);
Which is not valid.
Instead if you need length or sum of two arrays and then divide, you could sum up all the elements and then divide the two values.
You can't divide array like this (num1/num2)
Code snippet of one method how to do division of arraya
public static double answer(double[] num1, double[] num2){
//assumimg both array is of equal length
for (int i=0;i<num1.length;i++){
double result = num1[i]/num2[i];
}
}
As already been mentioned you can't divide arrays to each other, but their elements.
Change your answer function so instead of two arrays of double it takes two double and returns the result:
//num1 & num2 are double, not array
public static double answer(double num1, double num2){
return (num1/num2);
}
Remove tripMPG[count] = answer(tripMiles, gallons); from right after the while loop and instead add the following line at the end of your while loop right before count++;:
tripMPG[count] = answer(tripMiles[count], gallons[count]);
So your while should look like this:
while (count <= 9){//start while
System.out.println("Enter a description of this trip");
tripName[count] = scan.next();
System.out.println("How many miles did you drive?");
tripMiles[count] = scan.nextDouble();
System.out.println("How many gallons of gas did you use on this trip");
gallons[count] = scan.nextDouble();
tripMPG[count] = answer(tripMiles[count], gallons[count]);
count++;
}//end while

Why doesn't my "While Loop" print the computation of finding the average "score"?

I am writing a program that reads a sequence of positive integers input by the user. User will only enter one integer at a time.Then it will compute the average of those integers. The program will end when user enters 0. (0 is not counted in the average).The program will print out the average once the program ends.
Question: My code stops working when I gets to the while loop hence it doesn't compute the input by user, hence prints out nothing. Why doesn't my while loop compute the average from the user's inputs? Appreciate your guidance :)
import java.util.Scanner;
public class AverageOfIntegers {
public static void main(String[] args) {
int integer;
double sum;
sum = 0;
double average;
Scanner input = new Scanner(System.in);
int count; count = 0;
average = 0;
System.out.println("Please enter an integer: ");
integer = input.nextInt();
while (integer != 0) {
count = count + 1;
sum = sum + integer;
average = sum / count;
}
System.out.println("Average = " + average);
}
}
This is because you are never actually summing over more than one integer. The user only ever enters one number. As a result your loop is essentially acting on just the one number. You need to put the input inside the while loop and save a running sum and count there. Something more like this
while (integer != 0) {
count += 1;
sum += integer;
average = sum / count;
integer = input.nextInt();
}
Explanation
First of all, when you define data types, you can set their default value in the definition. Ex:
double sum = 0;
vs
double sum;
sum = 0;
Secondly, sum = sum + integer; is the same as: sum += integer;
Thirdly, count = count + 1; is the same as: count += 1 OR (and better yet), count++;
As for your actual algorithm, there is one problem and one suggestion:
you are not changing integer's value after each loop. So, you can
either do that in the while condition: while ((integer =
input.nextInt()) != 0) { or, at the end of each loop:
while (integer != 0) {
count ++;
sum += integer;
average = sum / count;
integer = input.nextInt();
}
This is a suggestion for technically better code (in my opinion), but it looks better, is more intuitive and requires less calculations to calculate the average after the while loop is done instead of during. That way, you only calculate it once, where needed, vs. every loop, which is not needed.
________________________________________________________________________________
The Code (complete class)
public class AverageOfIntegers {
public static void main(String[] args) {
int integer;
double sum = 0;
double average = 0;
Scanner input = new Scanner(System.in);
int count = 0;
System.out.println("Please enter an integer: ");
// set integer = to the nextInt() while looping so it calculates properly
while ((integer = input.nextInt()) != 0) {
count ++;
sum += integer;
}
average = sum / count; // calculate the average after the while-loop
System.out.println("Average = " + average);
}
}
________________________________________________________________________________
Example input/output:
Please enter an integer:
5
10
15
0
Average = 10.0
So it did 5 + 10 + 15 = 30 (which is the sum), and then the average is 30 / 3 (30 is the sum, 3 is the count), and that gave you Average = 10.0.
You need to move integer = input.nextInt(); inside the loop, so your program will collect inputs in a loop. See the corrected version:
import java.util.Scanner;
public class AverageOfIntegers {
public static void main(String[] args) {
int integer = 0, count = 0;
double sum = 0.0, average = 0.0;
Scanner input = new Scanner(System.in);
System.out.println("Please enter an integer: ");
integer = input.nextInt();
while (integer != 0) {
count = count + 1;
sum = sum + integer;
System.out.println("Please enter an integer: ");
integer = input.nextInt();
}
average = sum / count;
System.out.println("Average = " + average);
}
}
The problem is that the input.nextInt() should be part of the loop. The way you wrote it, the code gooes into an infinite loop whenever the first input is non-zero. Instead, do:
while ((integer = input.nextInt()) != 0) {
count = count + 1;
sum = sum + integer;
average = sum / count;
}
In the loop:
while (integer != 0) {
count = count + 1;
sum = sum + integer;
average = sum / count;
}
This will only stops when integer is 0, but this variable is not changing in the loop, so it will never be 0 if it wasn't already in the first place.
According to what you said you want to do, you should probably repeat the call to integer = input.nextInt(); inside your loop, lke this:
System.out.println("Please enter an integer: ");
integer = input.nextInt();
while (integer != 0) {
count = count + 1;
sum = sum + integer;
System.out.println("Please enter an integer: ");
integer = input.nextInt();
}
average = sum / count;
Also, as others have said, you only need to compute the average once after the loop, so I moved it too.

Categories