平均文件中的数据

时间:2013-11-06 23:20:11

标签: java file

我正试图平均每个学生的成绩。我已经在我的代码输出中成功列出了学生姓名及其成绩,但最后一步是输出成绩的平均值。这是代码:

import java.util.Scanner; 
import java.io.*;         

public class Grades_Data
{
public static void main(String[] args) throws IOException
{

  Scanner keyboard = new Scanner(System.in);

 String filename = "student_data.txt";


  File file = new File("student_data.txt");
  Scanner inputFile = new Scanner(file);


  while (inputFile.hasNext())
  {

     String firstName = inputFile.next();
     String lastName = inputFile.next();
     String gradeone = inputFile.next();
     String gradetwo = inputFile.next();
     String gradethree = inputFile.next(); 


     System.out.println("first name: " + firstName + "\tlast name: " + lastName + "\tgrade one: " + gradeone + 
     "\tgrade two: " + gradetwo + "\tgrade three: " + gradethree);
  }
  inputFile.close();
}
}

这是我的代码的输出:

first name: Willis  last name: McGee    grade one: 86   grade two: 91   grade three: 78
first name: Gladis  last name: Knight   grade one: 79   grade two: 93   grade three: 88
first name: John    last name: Wayne    grade one: 92   grade two: 89   grade three: 88
first name: Ginny   last name: Weasley  grade one: 68   grade two: 73   grade three: 89

我需要在每行末尾用平均成绩说“平均:”,使用他们的一年级,二年级和三年级(三个等级的总和除以3)< / p>

3 个答案:

答案 0 :(得分:0)

int average = ( Integer.parseInt(gradeone ) +  Integer.parseInt(gradetwo ) + Integer.parseInt(gradethree ) ) / 3;


  System.out.println("first name: " + firstName + "\tlast name: " + lastName + "\tgrade one: " + gradeone + 
     "\tgrade two: " + gradetwo + "\tgrade three: " + gradethree + "\taverage: " + average );

添加此内容。 您需要将String值解析为Integer,并计算平均值

答案 1 :(得分:0)

将字符串解析为int(将它们加在一起除以3)

int average = (Integer.parseInt(gradeOne) + Integer.parseInt(gradeTwo) + Integer.parseInt(gradeThree))/3;

将输出添加到字符串中:

System.out.println("first name: " + firstName + "\tlast name: " + lastName + "\tgrade one: " + gradeone + 
     "\tgrade two: " + gradetwo + "\tgrade three: " + gradethree  + "\taverage: " + average);

答案 2 :(得分:-1)

试试这个  System.out.println(“名字:”+ firstName +“\ tlast name:”+ lastName +“\ tgrade one:”+ levelone +      “\ tgrade two:”+ gradetwo +“\ tgrade three:”+ gradethree +“\ tAverage:”+(gradeone + gradetwo + gradethree)/ 3 );