I pass a file into the method. Then, I read the method by line. After that, if the line fulfills my condition, I will read the line by token-based, and update i. My question is, from the output, It looks like my I do not successfully update because my output is NaN. Could you help me to take look at this method, and tell me is anywhere going wrong?
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);
}
}
}
My output is :
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