为什么我会在Java中打印“ NaN”?

时间:2019-11-02 07:22:11

标签: java file-processing

我将文件传递给方法。然后,我逐行阅读该方法。之后,如果该行满足我的条件,我将基于令牌读取该行,并更新i。我的问题是,从输出来看,由于我的输出是NaN,看来我未成功更新。您能帮我看看这种方法,并告诉我哪里出了问题吗?

import java.util.*;
import java.io.*;

public class ReadingData {

    static Scanner console=new Scanner(System.in);

    public static void main(String[] args)throws FileNotFoundException{
        System.out.println("Please input a file name to input:");
        String name1=console.next();
        Scanner input=new Scanner(new File(name1));
        choosegender(input);    
    }

    public static void choosegender(Scanner input){
        boolean judge=false;
        while(judge==false) {
            System.out.println("Parse by gender(m/f/M/F):");
            String gender=console.next().toUpperCase();
            if(gender.contains("F")||gender.contains("M")) {
                count(input,gender);
                judge=true;  
            }else {
                System.out.println("Wrong...please select again!");
            }
        }
    }

    public static void count(Scanner input,String gender){
        int i=0;
        int totalage=0;

        while(input.hasNextLine()) {
            String line=input.nextLine();

            if(line.contains(gender)) { 
                Scanner token=new  Scanner(line);
                int id=token.nextInt();
                String name=token.next();
                String sex=token.next();
                int age=token.nextInt();
                i++;
                totalage=totalage+age;
           }
        }

        double average=(double)totalage/i;
        if(gender.equals("F")) {
            System.out.printf("the number of female is "+" "+i+",and the average age is %.1f\n ",average);
        }else {
            System.out.printf("the number of male is"+" "+i+",and the average age is %.1f\n",average);
        }
    }
}

我的输出是:

Please input a file name to input:
student.txt
Parse by gender(m/f/M/F):
f
the number of female is  0,and the average age is NaN

2 个答案:

答案 0 :(得分:0)

NaN代表不是数字

在javadoc中,常量字段NaN分别在Float和Double Classs中声明如下。

公共静态最终浮点数NaN = 0f / 0f; 公共静态最终双精度NaN = 0d / 0d;

答案 1 :(得分:0)

如果将floatdouble的数字除以0,则会得到NaN(不是数字,请参见@Anup Lal的答案)

在您的情况下,如果没有一行包含gender,则i将是0,而您的平均值将是NaN