currently working on an assignment and I need to read in a file of numbers and display the total amount of numbers, total even numbers, total odd numbers, and the averages of all three. I am currently struggling to find the average of the even numbers and the odd numbers. I have to display the average of the even number and the average of the odd numbers. I found the total average by using parseInt to convert the string of numbers i read in to ints so i could calculate the average but when i tried to do the same for even and odd numbers i couldnt get it to work
here is my current code:
public class Homework1 {
public static void main(String[] args) throws IOException {
// reads file in
File num = new File("numbers.txt");
Scanner inputFile = new Scanner(num);
// creates rounding object
DecimalFormat rounding = new DecimalFormat("#.##");
// neccesary variables
int count = 0;
double numbers =0;
int evenNum =0;
int oddNum =0;
double avg;
double evenAvg;
double oddAvg;
double sum = 0.0;
double evenSum = 0.0;
double oddSum = 0.0;
// reads in numbers file until last line is read
while(inputFile.hasNext())
{
String nums = inputFile.nextLine();
// converts string to ints so numbers can be added
sum += Integer.parseInt(nums);
// converts string to ints to so odd/even nums can be distinguished
numbers = Integer.parseInt(nums);
// updates total number count
count++;
// separates evens from odds
if(numbers % 2 == 0)
{
evenNum++;
evenSum += Integer.parseInt(nums);
}
else
oddNum++;
evenSum += Integer.parseInt(nums);
}
// calculates total num average
avg = sum/count;
// evenAvg =
// oddAvg =
// output of credentials and results
System.out.println("There are " +count+ " numbers in the file"+"\n");
System.out.println("There are " +evenNum+ " even numbers"+"\n");
System.out.println("There are " +oddNum+ " odd numbers"+"\n");
System.out.println("The total average value is " +rounding.format(avg)+"\n");
System.out.println("The odd number average is " +rounding.format(evenAvg)+"\n");
System.out.println("The even number average is " +rounding.format(oddAvg)+"\n");
}
Output:
There are 982 numbers in the file
There are 474 even numbers
There are 508 odd numbers
The total average value is 50362.43
okay so I corrected the if/else statements and added the brackets and this fixed the problem i was having
oddNum++;
oddSum += Integer.parseInt(nums);
Related
The instructions are the following:
Write a method called inputThenPrintSumAndAverage that does not have any parameters.
The method should not return anything (void) and it needs to keep reading int numbers from the keyboard.
When the user enters something that is not an int then it needs to print a message in the format "SUM = XX AVG = YY". XX represents the sum of all entered numbers of type int.
YY represents the calculated average of all numbers of type long.
I've coded the following method but I keep getting the incorrect average. What can I change to get the correct average?
public static void inputThenPrintSumAndAverage(){
Scanner scanner = new Scanner(System.in);
int sum = 0, counter = 0;
long average = 0L;
while(true) {
boolean number = scanner.hasNextInt();
if(!number)
{
counter++;
break;
}
else {
int digit = scanner.nextInt();
sum += digit;
counter++;
}
}
average = sum / counter;
System.out.println("SUM = " + sum + " AVG = " + average);
}
The following should do:
if(!number)
break;
Your average is wrong because you are incrementing "counter" more than you should.
Of course in the end you are going to have to add one more if statement to make sure you are not attempting to divide by counter if the counter is zero. In that case, an average is undefined.
Also, as others have pointed out in the comments, it is entirely unclear to us what you mean when you say "I keep getting the incorrect average", and we generally frown upon questions worded so vaguely. But if by any chance a "correct average" for you means an average with decimals, then you should use a double instead of a long for your average, and you should cast your counter to double before dividing, so as to force a double division instead of a long division.
Use scanner.hasNextInt() to read util a non-integer value is supplied as input:
public static void inputThenPrintSumAndAverage() {
Scanner scanner = new Scanner(System.in);
int number, sum = 0, counter = 0;
long average = 0L;
while (scanner.hasNextInt()) {
number = scanner.nextInt();
sum += number;
counter++;
}
if(counter != 0){
average = sum / counter;
}
System.out.println("SUM = " + sum + " AVG = " + average);
}
Note that you should check the value of counter to avoid a division by zero.
If you want the average to be in decimals, change the type of average to double: double average; and cast the division to double: average = (double) sum / counter;.
package gradeAvg;
import java.util.Scanner;
//Grade Average calculater
public class GradeAvg {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
System.out.print("Please Enter the first grade being added to the average:");
double average = input.nextInt();
System.out.print("The average is now: " + average + " Please enter the second grade being averaged:");
average += input.nextInt() ;
System.out.print("The average is now: " + average + " Please enter the third grade being averaged:");
average += input.nextInt() / 2;
System.out.print("The average is now: " + average + " Please enter the fourth grade being averaged:");
average += input.nextInt() / 2;
System.out.print("The average is now: " + average + " Please enter the fifth grade being averaged:");
average += input.nextInt() / 2;
input.close();
System.out.print(average);
}
}
Hey guys, I'm really new to java, and pretty terrible at math, I'm supposed to be making a program that allows the user to input a value, have it averaged out, print it out, and then allow the input of another value, have it averaged, and print, and continue. Am i going wrong when I divide by 2 at the end of each input or what?
Average is the sum of all the numbers divided by the number of numbers in the sum.
What you are doing here is not average. You are adding the half of every new number to the total sum. I don't what you are doing here.
Just to make things more understandable, let's make a sum and a counter:
public class GradeAvg {
public static void main(String[] args) {
int sum;
int counter;
// ...
}
}
Each time you ask for a number, you increment the counter and add the new number to sum:
int newNumber;
// ask for input
newNumber = input.nextInt()
sum += newNumber;
counter++;
You can then output the average like this:
System.out.println("The average is: " + (double)sum / counter);
That's wrong. each number you add weight 50% against the other numbers.
you need to keep track of the count (number of elements) and the sum and each time divide the sum by the number of elements.
so each time you add a number the function should be:
(OLD_AVERAGE*OLD_COUNT+NEW_NUMBER)/(OLD_COUNT+1)
or just use SUM and COUNT and each time AVERAGE=SUM/COUNT.
inc. count by 1 every new number.
inc sum by the number entered.
complete working solution... hope it helps...
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double sum = 0;
int count = 1;
double average = 0;
System.out.print("Please Enter the " + count + " grade being added to the average:");
for (; count <= 5;) {
sum = sum + input.nextInt();
average = sum / count;
System.out.println("The average is now: " + average);
count++;
if (count <= 5)
System.out.println("Please enter the " + count + " grade being averaged:");
}
input.close();
}
I am trying to write a Java program that takes in a potentially infinite number of values - and once the user enters a negative number, the program stops, computes the average of all of the entered numbers (excluding the negative one) and prints out how many numbers were entered (once again, not the negative one) as well as the average.
Below is the code I currently have. When I try to run the program, it does not computer the average correctly and you have to enter a couple consecutive negative numbers for it to finally stop the program.
To test the arithmetic and the rest of the program, I inserted a statement that would close the program if the word "negative" was entered rather than a negative number. When did this, the average and count and everything else worked just like it was made to. Essentially, the problems start to occur when I try to stop the program after a negative number.
I am a beginning programmer and this has been driving me crazy for a couple hours. Any help is greatly appreciated!
import java.util.*;
import java.lang.Math;
import java.io.IOException;
import java.io.InputStream;
public class Average
{
public static void main(String[] args)
{
Scanner numInput = new Scanner(System.in);
double avg = 0.0;
double count = 0.0;
double sum = 0.0;
System.out.println("Enter a series of numbers. Enter a negative number to quit.");
while (numInput.hasNextDouble())
{
double negNum = numInput.nextDouble();
if (negNum >= 0)
{
sum += numInput.nextDouble();
count++;
avg = sum/count;
}
else
{
System.out.println("You entered " + count + " numbers averaging " + avg + ".");
break;
}
}
}
}
You should use: sum+=negNum; instead of sum += numInput.nextDouble();
As it is now, your program, reads a number and if it is not negative it reads another number and adds it to the sum.
Also, you should compute the average only once in the else block.
You are reading a new number to compute the sum.
It should be
sum += negNum;
You have already received the number entered by the user in line:
double negNum = numInput.nextDouble();
You should add this number itself to sum rather than asking for another number from user by calling numInput.nextDouble() again. So the fixed code would be:
public static void main(String[] args){
Scanner numInput = new Scanner(System.in);
double avg = 0.0;
double count = 0.0;
double sum = 0.0;
System.out.println("Enter a series of numbers. Enter a negative number to quit.");
while (numInput.hasNextDouble())
{
double negNum = numInput.nextDouble();
if (negNum >= 0)
{
sum += negNum;
count++;
avg = sum/count;
}
else
{
System.out.println("You entered " + count + " numbers averaging " + avg + ".");
break;
}
}
}
Sample Run:
Enter a series of numbers. Enter a negative number to quit.
2
3
-1
You entered 2.0 numbers averaging 2.5.
Change
sum += numInput.nextDouble(); // reading next value again
to
sum += negNum;
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);
Working on a project where the user input determines the size of an array. Afterwards the user inputs values and receives the sum. Finally the program shows the user the percentage of each value to the total. For example if the array size is 4 and a[0] = 2, a[1] = 1, a[2] = 1, and a[3] = 2 it will show "2, which is 33.333% of the sum" "1, which is 16.666% of the sum" etc. The problem I have is that after the array and sum are determined and I try to find the percentage I get 0. Is the sum reset to 0 since it's a different for loop?
import java.util.Scanner;
public class CountIntegersPerLine
{
public static void main(String[] args)
{
int elements;
int arraySize;
int sum = 0;
int percentage;
System.out.println("How many numbers will you enter?");
Scanner keyboard = new Scanner(System.in);
//Length of array is determined by user input
arraySize = keyboard.nextInt();
int[] array = new int[arraySize];
System.out.println("Enter 4 integers, one per line");
for (elements = 0; elements < arraySize; elements++)
{
//Gather user input for elements and add the total value with each iteration
array[elements] = keyboard.nextInt();
sum = sum + array[elements];
}
System.out.println("The sum is " + sum);
System.out.println("The numbers are:");
for (elements = 0; elements < arraySize; elements++)
{
//Display the percent that each value contributes to the total
percentage = array[elements] / sum;
System.out.println(array[elements] + ", which is " + percentage + " of the sum.");
}
System.out.println();
}
}
Integer division will result in a zero value when the numerator is less than the denominator. You should declare percentage as a float or a double.
int percentage;
...
...
...
percentage = array[elements] / sum;
and you will need to cast the division operation in your case to preserve the value:
percentage = (double)array[elements] / sum;
Try declaring the sum variable as a double (or float):
double sum = 0.0;
Why? because in this line:
percentage = array[elements] / sum;
... You're performing a division between two integers, and all the decimals will be lost. You can verify that this is indeed the case, for example try this:
System.out.println(1/3); // it'll print 0 on the console
The solution to this problem is to have either one of the division's operands as a decimal number, by declaring as such their types (as I did above) or by performing a cast. Alternatively, this would work without changing sum's type:
percentage = array[elements] / ((double)sum);