I am fairly new to java and I'm trying to code to find the average. I understand that the average is adding all the numbers and then dividing the sum by the number of numbers but I'm not really sure how to code that. My guess is that I'd need a for loop but I don't know what to do from there. The program basically asks for a file to be read and then calculate the average. Here's the code I have so far:
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
public class Calculations
{
public static void main(String[] args) throws FileNotFoundException
{
System.out.println("Please enter a file name");
Scanner keyboard = new Scanner(System.in);
String filename = keyboard.next();
Scanner reader = new Scanner (new File(filename));
int length = reader.nextInt();
double [] num = new double[length];
double [] num2 = new double[length];
System.out.println("The numbers are:");
for(int i = 0; i < length; i++)
{
num[i] = reader.nextDouble();
System.out.println(num[i]);
}
}
}
The file I would be using is list.txt which contains:
20
1.1 2 3.3 4 5.5 6 7 8.5 9 10.0
11 12.3 13 14 15.5 16.1 17 18 19.2 20.0
The mean should be 10.625. Any help is deeply appreciated. Thank you in advance.
Just introduce a new variable sum, initialize it to 0, and add the elements to the variable while you are printing them.
System.out.println("The numbers are:");
double sum = 0; //new variable
for(int i = 0; i < length; i++)
{
num[i] = reader.nextDouble();
sum += num[i];
System.out.println(num[i]);
}
sum /= (double) length; //divide by n to get the average
System.out.print("Average : ");
System.out.println(sum);
It appears that you're simply having trouble computing the average; I'll address that issue here:
In Java 7 and below, use a for loop:
double sum = 0; //declare a variable that will hold the sum
//loop through the values and add them to the sum variable
for (double d : num){
sum += d;
}
double average = sum/length;
In Java 8 you can use a Stream to compute the average
double sum = Arrays.stream(num).sum(); //computes the sum of the array values
double average = sum/length;
Related
I've written some code that has a scanner read from a text file on my computer, but when running the code, the scanner only reads every other number that's in the text file.. any ideas?
Note: For the grades.txt, this is the file
"3 8 1 13 18 15 7 17 1 14"
import java.util.*;
import java.io.*;
public class GradeAverage
{
public static void main(String[] args) throws IOException
{
Scanner scanner = new Scanner(new File("C:\\Users\\Media - Graphics\\Documents\\SCHOOL\\NCVPS\\GradeAverage\\grades.txt"));
int i = 0;
int sum = 0;
int lineNumber = 0;
int average = 0;
while(scanner.hasNextInt()){
System.out.println(scanner.nextInt());
sum = sum+scanner.nextInt();
lineNumber++;
}
System.out.println("The sum of the numbers: "+sum);
System.out.println("The number of scores: "+lineNumber);
average = sum/lineNumber;
System.out.println("The average of the numbers: "+average);
}
}
Here's what it outputs:
3
1
18
7
1
The sum of the numbers: 67
The number of scores: 5
The average of the numbers: 13
Every time you call nextInt() in your loop, you consume one int. So when you do
System.out.println(scanner.nextInt());
sum = sum+scanner.nextInt();
You consume two int(s). You want something like
int t = scanner.nextInt();
System.out.println(t);
sum += t;
Also your average is currently an int (I would expect a float or double).
double average = sum/(double)lineNumber;
Don't forget to remove int average = 0; (or modify this and average accordingly).
I need to write a code where you insert 10 grades and get back the average of those ten grades. I know how to do it, except I don't know how to calculate the sum of all the grades. I found on this site this code:
public int sumAll(int... nums) { //var-args to let the caller pass an arbitrary number of int
int sum = 0; //start with 0
for(int n : nums) { //this won't execute if no argument is passed
sum += n; // this will repeat for all the arguments
}
return sum; //return the sum
}
so I wrote my code like this and it worked!:
import java.util.Scanner;
public class Loop7 {
public static void main(String[] args) {
Scanner scan = new Scanner (System.in);
System.out.println("Please enter how many grades you want to insert : ");
int num1 = scan.nextInt();
int num;
double sum =0;
for(int i= 0; i<num1; i++)
{
System.out.println("Please enter a grade: ");
num = scan.nextInt();
sum += num;
}
System.out.println("the average is: "+(sum)/num1);
}
so my question is what sum+=num; mean? how does that line give me the sum? and why I had to write double sum= 0?
Over here I explain each of those lines to better help you understand this code.
public class Loop7 {
public static void main(String[] args) {
Scanner scan = new Scanner (System.in); //this is what allows the user to input their data from the console screen
System.out.println("Please enter how many grades you want to insert : "); //this just outputs a message onto the console screen
int num1 = scan.nextInt(); //This is the total number of grades the user provides and is saved in the variable named num1
int num; //just a variable with nothing in it (null)
double sum =0; //this variable is to hold the total sum of all those grades
for(int i= 0; i<num1; i++) //loops as many times as num1 (if num1 is 3 then it loops 3 times)
{
System.out.println("Please enter a grade: "); //output message
num = scan.nextInt(); //every time the loop body executes it reads in a number and saves it in the variable num
sum += num; //num is then added onto sum (sum starts at 0 but when you add 3 sum is now 3 then next time when you add 1 sum is now 4 and so on)
}
System.out.println("the average is: "+(sum)/num1); //to get the average of a bunch of numbers you must add all of them together (which is what the loop is doing) and then you divide it by the number of items (which is what is being done here)
}
sum += num; Means that your sum which is declared 0 is added with num which you get from the console. So you simply make this: sum=sum+num; for the cycle. For example sum is 0, then you add 5 and it becomes sum=0+5, then you add 6 and it becomes sum = 5 + 6 and so on. And it is double because you are using division.
The reason you needed to write
double sum = 0.0;
is because you needed to initialize the sum first. Next the
sum += num;
means
sum = sum + num;
just in a more simple way.
I think I have swapped the first and last numbers of a dynamic array with each other and am at a total loss as to how to print the array with the numbers swapped.
Ideally, with the program working, the user is supposed to enter in the number of numbers they want to enter and then they will type each number in individually. Then it is supposed to output (along with standard deviation, the mean, and the original array order) the array in order, except the first number entered and the last number entered are switched. How would you go about printing the new array with the switched numbers?
Here is my code so far:
import java.util.Scanner;
import java.lang.Math;
public class Project_1 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("How many numbers would you like to enter? ");
int N = scan.nextInt();
float sd, mean;
float Sum = 0;
float Square = 0;
float [] numbs = new float[N];
System.out.println("Enter your numbers below: ");
for (int i = 0; i < N; i++){
numbs[i] = scan.nextFloat();
Sum += numbs[i];
}
mean = Sum/N;
scan.close();
for (int j = 0; j < N; j++){
Square = (numbs[j] - mean) * (numbs[j] - mean);
}
sd = (float)Math.sqrt(Square/N);
System.out.println("The mean is: " + mean);
System.out.println("The standard deviation is: " + sd);
for (int k = 0; k < N; k++){
if (k == N-1){
System.out.print(numbs[k]);
}else{
System.out.print(numbs[k] + ", ");
}
}
float lastNumb = numbs[numbs.length-1];
numbs[numbs.length-1] = numbs[0];
numbs[0] = lastNumb;
}
}
You can swap the integers by doing the following,
int temp = numbs[N-1];
numbs[N-1] = numbs[0];
numbs[0] = temp;
Hope this helps :)
I did not realize that I would just have to enter another simple if statement to print it out. I was confused as to where the edited array was saving to, not realizing that it was just saving to the original array. Thank you all for the help.
In the end this is what I used for the code (in regards to my program specifically):
float lastNumb = numbs[numbs.length-1];
numbs[numbs.length-1] = numbs[0];
numbs[0] = lastNumb;
for (int g = 0; g < N; g++){
if (g == N-1){
System.out.print(numbs[g]);
}else{
System.out.print(numbs[g] + ", ");
}
Heres the output:
How many numbers would you like to enter? 5
Enter your numbers below:
1
2
3
4
5
The mean is: 3.0
The standard deviation is: 0.8944272
1.0, 2.0, 3.0, 4.0, 5.0
5.0, 2.0, 3.0, 4.0, 1.0
I'm writing a program which should take five doubles from user input and return the average of them.
I want the program to take an input like
5.0 8.0 5.0 7.0 5.0
and return
6.0
Here is my code:
import java.util.Scanner;
public class findAverage {
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
// Initialise the array
float[] numberArray;
float total = 0;
// Allocate memory for 5 floats
numberArray = new float[5];
for(int i = 0; i < 5; i++){
numberArray[i] = keyboard.nextInt();
total += numberArray[i];
}
// Find the average
float average = total / 5;
System.out.println(average);
}
}
Right now, that code takes user input 5 separate times and computes the average. How do I make it so the user can input 5 floats on the same line and have the program find the average?
it is not possible to do it using Scanner, but...
YOU CAN DO IT LIKE THIS:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Avg {
public static void main(String[] args) throws IOException {
BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in));
float total = 0;
String line = keyboard.readLine();
String[] data = line.split("\\s");
for (int i = 0; i < data.length; i++) {
total += Float.parseFloat(data[i]);
}
// Find the average
float average = total / data.length;
System.out.println(average);
}
}
it will read all the floats entered in one line and print the average when you hit "enter".
If you want to be able to take an arbitrary number (N) of parameters and calculate the average without O(N) memory complexity, you can use the below.
Just make sure that you pass a non-number at the end of your list of parameters, like a 'a' or anything else that the Scanner doesn't ignore to make it stop.
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
double avg = 0.0;
for (int i = 1; ;i++)
{
if (!keyboard.hasNextDouble()) break;
double next = keyboard.nextDouble();
avg = (avg * (i - 1) + next) / i;
}
System.out.println(avg);
}
I am new to Java and I would like some help. I have to solve this problem and I have it almost 90% solved:
Prompt the user to enter number of students. It must be a number that is perfectly divisible by 10 i.e. (number % 10) = 0
Check user input. If user input is not divisible by 10, keep asking the user for input until he enter a right number.
Accept user input and generate that many random numbers in the range from 0 to 100.
Print a matrix of random numbers and calculate the sum and average of all these random numbers and print them to the user.
Format sum and average to three decimal points.
This is my code so far:
import java.text.DecimalFormat;
import java.util.Scanner;
public class Calculator10 {
public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);
int num;
do {
System.out.print("Enter a number: ");
num = user_input.nextInt();
} while(num % 10 != 0);
double numb;
DecimalFormat dec = new DecimalFormat("0.00");
for (int i=0; i<num; i++){
numb = Math.abs(Math.random() * ( 0 - 100 ));
System.out.print(" " +dec.format(numb) + " ");
}
}
}
As you can see, I have solved until the first part of # 4. I am not sure how I could sum all those random numbers displayed on the screen after user input. Of course, we have to store them in an array but I tried to do that but couldn't. So, how could I complete step #4 and 5? I would appreciate any help. Thanks a lot guys.
Here is how you should do it:
import java.text.DecimalFormat;
import java.util.Scanner;
public class Calculator10 {
public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);
int num;
do {
System.out.print("Enter a number: ");
num = user_input.nextInt();
} while(num % 10 != 0);
double numb;
double sum=0;
DecimalFormat dec = new DecimalFormat("0.00");
for (int i=0; i<num; i++){
numb = Math.random() * ( 100 - 0));
System.out.print(" " + dec.format(numb) + " ");
sum += numb;
}
System.out.println("The sum is: " + dec.format(sum));
System.out.println("The average is:" + dec.format(sum/num));
}
}
Please note that I have slightly changed the way you were generating the random numbers which obviates the need to use Math.abs(). Also see the following answer to see how to generate random numbers between two different values:
Generating random numbers with Java
You do not need to store them in an array. Just declare int sum = 0 at the start and do sum += numb each time you generate a random number. Also, you are generating random numbers in a strange way. Take a look at the java.util.Random class.