java - 为什么我会在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
解决方案
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;
推荐阅读
- c# - 如何从 xamarin.ios 中的 TouchUpInside 函数显示 UIView?
- sequelize.js - ValidationError [SequelizeValidationError]:验证错误:无效的验证器函数:nonEmpty,
- c# - “组件”类型是在未引用的程序集中定义的
- javascript - Javascript/Typescript 中类的交叉引用如何工作?
- python - 如何从 Oracle 数据库加载 UTF-8 编码的代理对?
- django - 一天和一周的用户总数
- javascript - 从 json 中的对象获取值时出错
- excel - Delphi,导出到 Excel 日期较低的问题 01.01.1900 OleException(800A03EC)
- sql - 如果延迟行在错误检查之前关闭会发生什么?
- blazor-server-side - 无法将 lambda 表达式转换为预期的委托类型,因为块中的某些返回类型不能隐式转换为委托 ret 类型