Java average method stuck - java

So guys this is my code. the code runs fine but I don't get the proper average. Could someone please fix it.
import java.util.Scanner;
public class test {
public static double Avg(int amt, int num) {
int tot = 0;
tot = tot + num;
int average = tot/amt;
return average;
public static void main(String[] args) {
double average_ICT_01 = 0;
Scanner sc = new Scanner(System.in);
ArrayList<Integer> ICT_01 = new ArrayList<Integer>();
for (int i=0; i<3; i++) {
int num = sc.nextInt();
ICT_01.add(num);
}
int length01 = ICT_01.size();
for (int c=0; c<3; c++) {
int num1 = ICT_01.get(c);
average_ICT_01 = Avg(length01,num1);
}
System.out.println(average_ICT_01);
}
}

The arithmetic average of n numbers is their sum divided by n. So a method for calculating the average of all the numbers in a vector should be:
public static double avg(List<int> vec){
//Sum all numbers
long sum = 0;
for(int i=0;i<vec.size();i++){
sum = sum + vec.get(i);
}
//Divide by the number of numbers
double avg = sum/vec.size();
//Return the average
return avg;
}

Related

finding the average of array then finding the number above the average to print

import java.util.Scanner;
public class ProjectFour {
public static void main(String args[]) {
int[] firstArray = {1,2,3,2,1,6,3,4,5};
System.out.println("this is the average of array : "+analyzeNumbers(firstArray));
System.out.println("These are the numbers above the average : "+aboveAvg(firstArray));
}
//finding the average
public static int analyzeNumbers(int[] firstArray){
int avg;
avg=sumArray(firstArray);
avg=avg/firstArray.length;
return avg;
}
//suming the array method
public static int sumArray(int[] firstArray){
int sum = 0;
for(int x=0;x<firstArray.length;x++){
sum+=firstArray[x];
}
return sum;
}
**this is where im running into problems im kinda stumpted**
// this is my method i cant figure out trying to take the average and find all the numbers in the array above the average and printing them.
public static int aboveAvg(int[] firstArray){
int[] aboveAvg;
aboveAvg = new int[0];
int x;
for(x=analyzeNumbers(firstArray);x<firstArray.length;x++){
aboveAvg+=firstArray[x];
}
return aboveAvg;
}
}
Try using a for loop.
int sum = 0;
for(int i = 0; i < firstArray; i++) {
int getSum = firstArray.get(i);
sum + getSum;
}
int average = sum / firstArray.length;
int[] aboveAverage;
for(int c = 0; c < firstArray; c++) {
if(firstArray.get(c) > average) {
aboveAverage.add(firstArray.get(c));
}
}
This aboveAvg function is completly wrong.
public static List<Integer> aboveAvg(int[] firstArray){
List<Integer> aboveAvg = new ArrayList<Integer>();
int Avg = analyzeNumbers(firstArray);
for(int i = 0; i<firstArray.length; i++)
{
if(firstArray[i] > Avg)
{
aboveAvg.add(firstArray[i]);
}
}
return aboveAvg;
}
Check your for loop and more examples about it
+= will sum two values, won't add new element on any array.
you have to define your return value correctly.
You can use List for create arrays, it's more flexible.

Series generation

I am trying to find out the sum of the series, 1/2! - 2/3! + 3/4! - 4/5! ... n. Sorry if this sounds awkward but the sum always shows up as 0.0. I can't figure out what's happening and I am just starting out. Can anyone kindly point out the mistake and suggest how to fix it? Thanks!
import java.util.Scanner;
public class Series {
/*
* Series design: 1/2! - 2/3! + 3/4! - 4/5! .. n
*/
static double sum = 0; static int n;
Scanner sc = new Scanner(System.in);
public static int fact(int n){
int fact = 1;
for (int i = 1; i<=n; i++){
fact *= i;
}
return fact;
}
void generate(){
double sign = 1.0; double term;
for (int i = 1; i<=n; i++){
term = i/fact(i+1) * sign;
sum += term;
sign *= -1;
}
}
void accept(){
System.out.println("Enter the value of n:");
n = sc.nextInt();
}
public static void main(String[] args){
Series o = new Series();
o.accept();
o.generate();
System.out.println("The sum of the series is: " +sum);
}
}
i and fact(i+1) are both ints, so you're performing integer division. Since i < fact(i+1), each such term will produce a zero.
You had the right idea with defining sign as a double, but since / and * have the same precedence, you're first performing an integer division and only then multiplying by the double sign. Moving it to the beginning of the expression should do the trick:
void generate(){
double sign = 1.0; double term;
for (int i = 1; i<=n; i++){
term = (sign * i) / fact(i+1);
sum += term;
sign *= -1;
}
}
Your problem is that i/fact(i+1) is an int division, so it is truncated to 0 (since it's smaller than 1).
Change it to (double)i/fact(i+1).
Alternately, you can write
term = sign*i/fact(i+1);
since sign is already double, so it would ensure sign*i would also be double, and the division would be a floating point division.
import java.util.Scanner;
public class Series {
static double sum = 0.0;
static int n=0;
static Scanner sc = new Scanner(System.in);
public static int fact(int n)
{
int fact = 1;
for(int i = 1; i<=n; i++){
fact *= i;
}
return fact;
}
static void generate(){
//because of static property
double sign = 1.0; double term;
for(int i = 1; i<=n; i++){
term = (i* sign)/fact(i+1) ;
sum += term;
sign *= -1;
}
}
static void accept(){
//because of static property
System.out.println("Enter the value of n:");
n = sc.nextInt();
}
public static void main(String[] args){
Series.accept();
Series.generate();
System.out.println("The sum of the series is: " +sum);
}
}

The mean and the standard deviation of the values in its array parameter

Here's My Code; and I can find an array with this and I would like to calculate the mean of the values (overall) after this I would like to calculate standard deviation of this but I couldn't understand the question exactly so I dont have a method for now. Here's the question for standard deviation (Write a method that takes two parameters --a set of int values in an array and a double value representing their mean-- and computes and returns the standard deviation of the values using the given mean.)
import java.util.*;
public class Test
{
final static int N = 100;
static int limit = 0;
static int[] list;
static int i, j;
static int sum = 0;
static Scanner scan = new Scanner (System.in);
public static int[] generateArray ()
{
System.out.print ("Enter your array limit: ");
limit = scan.nextInt();
list = new int[limit];
for(i = 0; i < limit; i++)
{
list[i] = (int) (Math.random() * 2 * N - N);
}
return list;
}
public static void printArray()
{
for(j = 0; j < limit; j++)
System.out.print (list[j] + "\t");
}
public static void meanArray()
{
sum = sum + list[j]; //PROBLEM HERE
System.out.println (sum);
}
public static void main(String[] args)
{
generateArray();
printArray();
meanArray(); //PROBLEM HERE
}
}
To generate the mean value, add up all values in your list and devide them by the number of values:
public static void meanArray() {
double result = 0;
for(int i : list) {
result += i;
}
result /= list.length;
System.out.println(result);
}

Function method for average numbers

public class Part4 {
public static void main(String args []) {
Random rand = new Random();
int total = 0;
for(int i = 0;i< 10;i++) {
total += rand.nextInt(101);
}
double avg = (double) total/10;
System.out.println("The average of 10 marks is " +avg);
}
}
My code works perfectly, however I don't know how to put my code in the procedure method. Can you please help me with that?
Do it like this. You can say with parameter amount with how many number you want to calculate the average.
public double calculateAverage(int amount) {
Random rand = new Random();
int total = 0;
for (int i = 0; i < amount; i++) {
total += rand.nextInt(101);
}
double avg = (double) total / amount;
System.out.println("The average of 10 marks is " + avg);
return avg;
}
The following example shows how to delegate the calculations to a method , how to call it by instantiating the class Part4
public class Part4
{
public double getAvgRandNum(int num)
{
Random rand = new Random();
int total = 0;
for(int i = 0;i< num ;i++)
{
total += rand.nextInt(101);
}
double avg = (double) total/num;
return avg;
}
public static void main(String args []) {
Part4 prt = new Part4()
double avgRes = prt.getAvgRandNum(10)
System.out.println("The average of 10 marks is " +avgRes);
}
}
In Main we are instantiating (creating an object of) class Part4.Once an object is created "prt" just use the dot operator to access (call) its method getAvgRandNum.
It seems like you're at a very early stage of learning Java, so I thought I'd pop in an even 'simpler' solution.
public class Part4
{
//This is the method you need to call
public static double calculateAverage(int amount) {
Random rand = new Random();
int total = 0;
for (int i = 0; i < amount; i++) {
total += rand.nextInt(101);
}
double avg = (double) total / amount;
return avg;
}
public static void main(String args []) {
//And this is how we call it
double avgRes = calculateAverage(10)
System.out.println("The average of 10 marks is " +avgRes);
}
}
Thanks to Moh123 and Mosa, I borrowed some code.

Return the amount of numbers below average

I am trying to write a program that returns the amount of numbers less than the average
For example, if I have the numbers 2, 3 and 4, the average would be (2.1+3.6+4.2)/3 = 3.3 and since 2.3 is below average it would return 1 as there is one number below the average.
I am getting an error that says
Type mismatch: cannot convert from double[] to int
My code:
public static void main(String[] args) {
double[] numbers = {2.1, 3.6, 4.2};
System.out.println(belowaverage(numbers));
}
public static int belowaverage(double[] ba) {
double sum = 0;
double average = 0;
for(int i = 0;i<ba.length;i++){
sum = sum + ba[i];
average = sum / ba.length;
if(ba[i]<average){
return ba;
}
}
You're trying to return the array ba which is the array holding your input data instead of the count.
You need to leave the computation of the average in your current for loop and then create a second for loop and an int count variable which you will increment each time you find a number in the ba array that is smaller than the average. Then outside of that loop you return count.
Also this line:
average = sum / ba.length;
Has to be outside of the first loop.
#Edit: others provided some code but it had either logical or compile time errors (not all of them I guess, the ones I checked) so here's a working version:
public static int belowaverage(double[] ba) {
double sum = 0;
double average = 0;
int count = 0;
for(int i = 0; i < ba.length; i++) {
sum = sum + ba[i];
}
average = sum / ba.length;
for(int i = 0; i < ba.length; i++){
if (ba[i] < average) {
count++;
}
}
return count;
}
You don't need to cast length to double as sum is of type double so the result will be promoted to the bigger type.
public static void main(String[] args) {
double[] numbers = {2.1, 3.6, 4.2};
System.out.println(belowaverage(numbers));
}
public static int belowaverage(double[] ba) {
double sum = 0;
int length = ba.length;
for (int i = 0; i < length; i++) {
sum += ba[i];
}
double average = sum / length;
int belowAvgCount = 0;
for (int i = 0; i < length; i++) {
if (ba[i] < average) {
belowAvgCount++;
}
}
return belowAvgCount;
}
This isn't going to work using only a single for loop, because you can't possibly compare anything to the average until you've calculated it.
Try separating your calculation of the average and the counting of terms below the average into two different loops:
public static int belowaverage(double[] ba) {
double sum = 0;
double average = 0;
for(double b : ba){
sum += b;
}
average = sum / ba.length;
int count = 0;
for(double b : ba){
if(b < average){
count++;
}
}
return count;
}
You need to work out the sum first, then compute the average and then count how many below this threshold.
try
public static int belowaverage(double[] ba) {
double sum = 0;
double average = 0;
int count = 0;
for(int i = 0;i<ba.length;i++){
sum = sum + ba[i];
}
average = sum / ba.length;
for(int i = 0;i<ba.length;i++){
if (ba[i] < average) count++;
}
return count;
}

Categories

Resources