Dylan Thomas Dylan Thomas - 7 months ago 39
Java Question

finding an int that is closest to the avg in java?

  1. The goal of this was to find nearest no. out of inputted no.s to the avg of the sum of the no.s

  2. For some reason it fails to output the correct answer near the final for loop.

  3. The code under here is fine

    import java.util.Scanner;
    import java.util.*;

    public class ClosesttoAvg{
    public static void main(String args[]){
    Scanner sc = new Scanner(System.in);
    System.out.println("input no. elements and then the elements to find
    closest to avg");
    double size = sc.nextInt(), load = 0;
    double array[] = new double[(int)size];

    //sort all the no.s into an array and add them all up into load

    for(int i = 0; i<size; i++){
    array[i] = sc.nextDouble();
    load = load + array[i];
    double avg = load/size, record = size, answer = 0;
    //record keeps the smallest distance, answer stores the closest no.,
    //problem is located here

  4. Here is where I have problems though, for some reason it does not save the correct variable

    for(int i = 0; i<size; i++){
    double dist = Math.abs(array[i]-avg);
    if(dist < record){
    answer = array[i];


Answer Source

I think that you should update record too. For now it is always size and that's why your answer can be overwritten.

In if in loop add record = dist;

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download