首页 > 解决方案 > 为什么我会在java中打印“NaN”?

问题描述

我将一个文件传递给该方法。然后,我逐行阅读该方法。之后,如果该行满足我的条件,我将基于令牌读取该行,并更新 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

标签: javafile-processing

解决方案


NaN stands for Not a Number.

In javadoc, the constant field NaN is declared as following in the Float and Double Classes respectively.

public static final float NaN = 0f / 0f; public static final double NaN = 0d / 0d;


推荐阅读