-4

The following example takes a sum Integers as program arguments and calculates the average out of them. But somehow it prints "NaN"

public static void main(String args[]) {
    int sum= 0; 
    for(int i= 0; i < args.length; i++) {
        sum= sum + Integer.parseInt(args[i]);
    }

    System.out.println("Average: " + (float)sum / args.length);
}

How it could evaluate to NaN?

1
  • 2
    Sounds like args is empty. Your code assumes otherwise. When you step through this in a debugger, what happens?
    – David
    Nov 24, 2015 at 17:45

1 Answer 1

6

I have tested your code:

public class Test {
    public static void main (String args[]) {
        int sum = 0;
        for(int i= 0; i < args.length; i++) {
            sum = sum + Integer.parseInt(args[i]);
        }
        System.out.println("Sum: " + sum);
        System.out.println("Average: " + (float)sum / args.length);
    }
}

I ran it as:

java Test 1 2 3

And the output was:

Sum: 6
Average: 2.0

Probably you forgot to pass arguments when running your java program? Because when I run it as:

java Test

I get:

Sum: 0
Average: NaN
5
  • I don't want to be that guy but how in the would so i add arguments in args? Im confused because I never initialized args?? so there is nowhere I can get the num. Can you be more clear? sorry again I'm learning java on my own so resources are very hard to come by... thank you again and happy thanks giving Frakcool! Nov 25, 2015 at 18:09
  • @DanielAndrews Can you clarify your comment? I'm not sure I have understood well enough what you mean: Are you asking how is args being filled? Without initializing it?
    – Frakcool
    Nov 25, 2015 at 18:11
  • Ok Frakcool, I totally understand whats going on. Im using eclipse so I ran it in terminal and added some numbers and I got my answer. Show I totally know what your talking about ty! Nov 25, 2015 at 18:14
  • haha @Frankcool.. nah.. I totally understand now.. I really appreciate your help :) I had to add the arguments in terminal.. xD I feel dumb now.. Nov 25, 2015 at 18:16
  • Oh don't worry :) Good luck then ^^
    – Frakcool
    Nov 25, 2015 at 18:18

Not the answer you're looking for? Browse other questions tagged or ask your own question.