用Java中的扫描仪读取文件
在本作业中,我们假设从txt文件中读取测试和家庭作业分数,并计算最终分数。由于我们尚未了解如何读取和写入文件,这是提供给我们的预制方法:用Java中的扫描仪读取文件,java,file,Java,File,在本作业中,我们假设从txt文件中读取测试和家庭作业分数,并计算最终分数。由于我们尚未了解如何读取和写入文件,这是提供给我们的预制方法: /****************************************************************************** * * Filename : GradeCalculatorFromFile.java. * Author: xxxxxxxxx * Date: 09/0
/******************************************************************************
*
* Filename : GradeCalculatorFromFile.java.
* Author: xxxxxxxxx
* Date: 09/025/2011
* Description: This program computes the scores of a list of students in the CSE155a class
*
******************************************************************************/
import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;
/* Provide a description of the class */
public class GradeCalculatorFromFile {
public static void main(String[] args) {
// Declare and initialise the variables as needed
int anthonyHopkinsTest = 0;
int anthonyHopkinsHomework = 0;
/*
* The following code enables the user to accept input from the
* keyboard. Keep this code as it is.
*/
Scanner scanner = null;
try {
scanner = new Scanner(new File("grades.txt"));
} catch (FileNotFoundException e) {
System.out.println("Error opening file. Please make sure that you have a grades.txt file in the same folder as GradeCalculator.class");
System.exit(0);
}
/*
* Add your code here to read the number of students and the scores Use
* scanner.next() to read a String Use scanner.nextInt() to read an int
*/
}
}
这是我们打算使用的txt文件:
4
Anthony Hopkins 80 90 95 87 80 78 25 17 20 22 21 24 19 22 21 23 24 21 20 25 20 55 56 110 30 20 25 8
John Smith 99 95 82 72 64 52 15 14 11 21 25 12 19 20 21 23 21 12 12 10 15 50 50 60 25 15 20 9
Pan Mei 85 92 72 45 82 78 22 13 16 22 24 10 18 12 21 24 25 10 11 14 20 58 51 95 28 14 28 7
Rafael Vega 99 45 87 52 87 99 25 25 21 21 14 19 19 25 25 20 20 18 20 24 20 60 60 60 25 16 23 8
问题是我们没有被教会如何从文件中获取信息。说明书上说要用扫描仪来评分,但我不知道怎么做。小组中的前21个数字是家庭作业,下3个是测试,最后4个是家庭作业。我知道如何用用户输入来做这类事情,但在从文件读取信息时却不知道。从文件读取信息与从用户输入读取信息是一样的?然后某种形式的for循环添加到他的分数上?试试看会发生什么。我试过:
anthonyHopkinsTest=scanner.nextInt();对于(inti=1;i<7;i++){System.out.println(anthonyHopkinsTest);}
,多次得到4。我把它读了,这很酷。如何选择要读取的行?请检查java文档中的扫描仪。