首页 > 解决方案 > 如何将字符串中的双打添加到双打数组列表中?

问题描述

我必须为 students.txt 文件中的每一行添加一个学生,并将其中的成绩添加到新学生。学生对象有4个属性,name(字符串)、last name(字符串)、number(int)和grades(arraylist double)

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;


public class readFile {

    public static void main(String[] args) {
        ArrayList<student> students = new ArrayList<>();
        int linecnt = 0;
        try(BufferedReader br = new BufferedReader(new FileReader("students.txt"))) {
            String line;
            while((line = br.readLine()) != null) {
                
                students.add(new student("", "", 0));
                Scanner scan = new Scanner(line);
                if(scan.hasNextDouble()) {
                    students.get(linecnt).addGrade(scan.nextDouble());
                }
                linecnt++;
                
            }
            
        }   catch(FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        
        

    }

}

当我运行它时,什么都没有发生,没有错误,只是一个空白区域。问题是什么?

标签: java

解决方案


你还没有说应该是什么输出。你的问题的答案是

如何将字符串中的双打添加到双打数组列表中?

String text = "12.34"; 
double value = Double.parseDouble(text);
arraylist.add(value);

推荐阅读