Use Scanner and File to read this file of vocabulary scores as measured by the General Social Survey from 1972 to 2004. Compute and display the mean score for both males and females.
I am unsure of how to seperate the lines into chunks by comma and to still retain the correct data.
Example of what the file contains: Female,7 Male,3 Male,6 Male,10 Female,10
public static void main(String[] args) throws FileNotFoundException {
File file = new File("scores.csv");
Scanner in = new Scanner(file);
String run = "";
int maleCount = 0;
int femaleCount = 0;
int maleScore = 0;
int femaleScore = 0;
while (in.hasNextLine()) {
String current = in.nextLine();
in.useDelimiter(",");
if (current.contains("f")) {
femaleCount++;
// add score onto femaleScore
}
else {
maleCount++;
// add score onto maleScore
}
double femaleAverage = femaleScore / femaleCount;
System.out.println(femaleAverage);
double maleAverage = maleScore / maleCount;
System.out.println(maleAverage);
}
in.close();
}
Your calculation was inside the while loop, meaning it would calculate this average once per line in the file, which is wrong. The code below assumes the format of the data is the same as stated in your post.
Female,7
Male,3
Male,6
Male,10
Female,10
public static void main(String[] args) throws FileNotFoundException {
File file = new File("scores.csv");
Scanner in = new Scanner(file);
String run = "";
int maleCount = 0;
int femaleCount = 0;
int maleScore = 0;
int femaleScore = 0;
while (in.hasNextLine()) {
String current = in.nextLine();
String[] split = current.split(",");
if (split[0].toLowerCase().contains("f")) {
femaleCount++;
femaleScore += Integer.parseInt(split[1]);
// add score onto femaleScore
} else {
maleCount++;
maleScore += Integer.parseInt(split[1]);
// add score onto maleScore
}
}
double femaleAverage = femaleScore / femaleCount;
System.out.println(femaleAverage);
double maleAverage = maleScore / maleCount;
System.out.println(maleAverage);
in.close();
}
If the data is different, post it here and I will edit the code accordingly