java Scanner拆分字符串

时间:2015-02-27 23:52:27

标签: java java.util.scanner delimiter

所以我坚持做家庭作业,只想得到一些帮助我有3个文本文件,其中包含多个学生姓名及其成绩的格式:

Student Name

Test 1: 93
______________
Student Name

Test 1: 99
_____________

I need to figure out a way to split the line where the grade is and skip the ------- that splits the students and their grades up. I would then need to parse the test grade into a variable so i could do calculations with it. 

     public void openFile() throws IOException {
                //opens text file
                try {
                    FileReader inputFile = new FileReader("C:\\Users\\Chris\\IdeaProjects\\workshop3\\src\\filereader\\file1.txt");
                    //delimiter from scanner object skips characters passed as parameters
                    kb = new Scanner(inputFile).useDelimiter("\n");
                    while(kb.hasNext()){
                        line = kb.next();
                        System.out.println(line);
                    }


                } catch (IOException e) {
                    e.printStackTrace();
                }

我现在遇到了这个方法的问题,我正在使用数组列表循环编写学生。但每次将某些内容写入指定文件时,它都会在文件中写入现有的学生信息。希望有人可以提供帮助。

public void writeFile(Student stud) throws IOException{
        try{
            PrintWriter outputFile = new PrintWriter(new FileOutputStream("C:\\Users\\Chris\\IdeaProjects\\workshop3\\src\\filereader\\file4.txt"));


            outputFile.println("\nStudent: " + stud.getName());
            outputFile.println("Midterm 1: " + stud.getMid1());
            outputFile.println("Midterm 2: " + stud.getMid2());
            outputFile.println("Final: " + stud.getFin());
            outputFile.printf("Average: %.2f"  ,stud.calculateAverage(stud.getMid1(),stud.getMid2(),stud.getFin()));


            outputFile.close();

        }catch(IOException e){

        }
    }

2 个答案:

答案 0 :(得分:0)

您可以在字符串类中使用split函数,例如。

String line= "Test:93";
String[] splits = line.split(":") // which would give {"Test","93"}

答案 1 :(得分:0)

由于您使用的是Scanner,因此已使用nextLine()作为分隔符的方法\n

  

学生姓名

     

测试1:99

     

我需要找出一种方法来分割成绩所在的行   跳过-------将学生和他们的成绩分开

参考你的帖子,你可以试试这个:

kb = new Scanner(inputFile);
int grade;
while(kb.hasNextLine()){
    line = kb.nextLine();//read complete line
    if(line.startsWith("----")) {
       continue;//skip it
    }
    if(line.contains(": ")) {
       //student grades
       grade = Integer.parseInt(line.split("\\:\\s")[1]);
    } else {
       //student name
    }
}

在这里,我写了这个成绩:Integer.parseInt(line.split("\\:\\s")[1])。由于您提到成绩由:分隔,line.split("\\:\\s")将为您提供一个字符串数组,其值除了分隔符,例如如果输入为Test 1: 99,则会提供["Test 1", "99"]。现在你需要int值进行计算,所以我使用了Integer.parseInt(String)