1 Attachment(s)
Help fixing my Java program! Reading files
Code Java:
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
import java.text.DecimalFormat;
public class EchoFileData
{
public static void main(String [] args) throws IOException
{
int grade;
int count = 0;
int total = 0;
int maxGrade = 0;
int minGrade = 0;
int passed = 0;
int gradeA = 0;
int gradeB = 0;
int gradeC = 0;
int gradeD = 0;
int gradeF = 0;
File inputFile = new File( "Grades.txt" );
Scanner scan = new Scanner( inputFile );
maxGrade = scan.nextInt ();
minGrade = scan.nextInt ();
while ( scan.hasNext() )
{
grade = scan.nextInt();
count++;
total += grade;
if(grade > maxGrade)
{
maxGrade = grade;
}
if (grade < minGrade)
{
minGrade = grade;
}
if (grade >= 60)
{
passed ++;
}
if (grade >= 90)
{
gradeA++;
}
if (grade >= 80 && grade < 90)
{
gradeB++;
}
if (grade >= 70 && grade < 80)
{
gradeC++;
}
if (grade >= 60 && grade < 70)
{
gradeD++;
}
if (grade < 60)
{
gradeF++;
}
}
System.out.println("The total number of students in the class is " + count + ".");
DecimalFormat decimalPlace = new DecimalFormat( "##.0" );
System.out.println("The class average test score is " + decimalPlace.format((double) (total)/ count) + ".");
System.out.println("The highest score is " + maxGrade + ".");
System.out.println("The lowest score is " + minGrade + ".");
System.out.println("The number of students who passed is " + passed + ".");
System.out.println("The number of students who received an A is " + gradeA + ".");
System.out.println("The number of students who received an B is " + gradeB + ".");
System.out.println("The number of students who received an C is " + gradeC + ".");
System.out.println("The number of students who received an D is " + gradeD + ".");
System.out.println("The number of students who received an F is " + gradeF + ".");
}
}
This is my code and I am importing a file and need to print out the number of students in the class, the average test score, the highest and lowest grade, and how many received each letter grade. I will attach the text file I imported.
My output says there is only 33 students and there should be 35. It was outputtingAttachment 1818 35 before I put in all the if statements to add to the number of each grade. Then it changed to 33 and I'm not sure how to fix it.
Re: Help fixing my Java program! Reading files
Your problem is here:
Code java:
maxGrade = scan.nextInt ();
minGrade = scan.nextInt ();
The counter is not increased for the first two lines you read. I would set the maxGrade to 0, and minGrade to 100, then remove those two lines.
Re: Help fixing my Java program! Reading files
Quote:
My output says there is only 33 students and there should be 35.
Is the program not reading some lines from the file? Print out the lines as they are read so you can see which lines are not being read.
Re: Help fixing my Java program! Reading files
Post retracted. Good advice already given..