HW-how to read a string from a text file
I received this homework assignment, it basically tells me to read GPAs of male and female students from a text file and then output averages to another text file.
This is an idea of what the file looks like that is read:
f 3.40
f 4.00
m 3.56
m 3.80
f 2.30
f 3.95
My question is how do I read whether the character before the gpa is "m" or "f"?
This is what I have so far:
Code :
import java.io.*;
import java.util.*;
public class HW2 {
public static void main (String[] args) throws FileNotFoundException {
double mGPA, fGPA;
String m,f;
double mGPAsum = 0;
double fGPAsum = 0;
int numberMales = 0;
int numberFemales = 0;
Scanner inFile=new Scanner(new FileReader("input.txt"));
PrintWriter outFile = new PrintWriter("outputGPA.txt");
while (inFile.hasNext()) {
if (inFile.equals("f")) {
double gpa = inFile.nextDouble();
fGPAsum += gpa;
numberFemales++;
}
if (inFile.equals("m")) {
double gpa = inFile.nextDouble();
mGPAsum += gpa;
numberMales++;
}
}
outFile.println("Sum female GPA = " + fGPAsum);
outFile.println("Sum male GPA = " + mGPAsum);
outFile.println("Female count = " + numberFemales);
outFile.println("Male count = " + numberMales);
fGPA = fGPAsum / numberFemales;
mGPA = mGPAsum / numberMales;
outFile.println("Average female GPA = " + fGPA);
outFile.println("Average male GPA = " + mGPA);
inFile.close();
outFile.close();
}
}
And this is what it's saying:
2 warnings found:
Warning: The local variable m is never read
Warning: The local variable f is never read
Re: HW-how to read a string from a text file
I'm pretty confused by your approach here. The inFile variable is a Scanner, right? So why are you comparing it to a String? That's not how you test the Scanner's input. I suggest reading the API as well as the tutorial to figure out how to correctly use Scanner. By the way, those links were the first 2 hits for googling "java scanner", which is a process you should try to get more accustomed to.
Re: HW-how to read a string from a text file