TibetanMassive
TibetanMassive

Reputation: 45

How do I avoid NaN?

I understand it's because the program thinks I'm dividing by O, but I'm not sure how to fix it in the program. The program works fine, though. It outputs the average the way I want it to, but I would like it to output <0.0> when there are no integers being sent from the main method.

public class Statistics {

private int count;
private int sum;
//private double average;

public Statistics() {
    this.count = 0;

}

public void addNumber(int number) {
    sum += number;

    count++;
}

public int getCount() {
    return this.count;
}

public int sum() {

    return sum;
}

public double average() {
    double average=0;
    average = this.count/(double)sum;
    return average;
}

public static void main(String[] args) {
    Statistics statistics = new Statistics();
    //statistics.addNumber(3);
    //statistics.addNumber(5);
   // statistics.addNumber(1);
    //statistics.addNumber(2);
   System.out.println("Count: " + statistics.getCount());
    System.out.println("Sum: " + statistics.sum());
    System.out.println("Average: " + statistics.average());
}

}

How can I re-write this average section to avoid that?

Upvotes: 0

Views: 367

Answers (2)

Mark Colby
Mark Colby

Reputation: 191

Just add an if statement to handle this edge case.

public double average() {
    double average=0;
    //added if statement to avoid diving by 0
    if(count==0){return 0.0;}
    average = this.count/(double)sum;
    return average;
}

Upvotes: 2

Doruk Eren Aktaş
Doruk Eren Aktaş

Reputation: 2337

First of all, your average function is not working right. avg = sum / count but your function does avg = count / sum. For printing when count is zero, check it with an if.

public double average() {
    // If there is nothing to average return zero
    if (this.count == 0) return 0.0;

    double average = 0;
    average = this.sum / (double)this.count;
    return average;
}

Upvotes: 2

Related Questions