亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

將文件讀入數組列表,但參數列表的長度不同

將文件讀入數組列表,但參數列表的長度不同

心有法竹 2022-09-22 10:23:48
我被困在一個文件IO的問題上?;旧?,有一個名為“學生”的類,還有一個名為“讀取學生”的方法,它將返回一個 ArrayList 對象。我被要求讀取一個文件,并通過單個空格將它們分成3個部分,并且不允許使用掃描儀。文件:艾米·摩爾 60克洛伊·斯科特 40我的問題是,(1)由于學生類只有兩個參數(字符串,雙精度),我如何將兩個字符串和一個雙精度添加到學生中?(2)學生班級提供的沒有toString()方法,我該如何打印出來?如果有人能幫助我,我將不勝感激。學生的構造函數是這樣的: public Student(String sstudent, double mmark) 已讀學生: public static ArrayList<Student> readStudent(String fName){到目前為止,我做了什么: ArrayList<Student> list=new ArrayList<Student>(); try{    BufferedReader br=new BufferedReader(new FileReader(fName));     String line;     while((line=br.readLine())!=null){        String[] splitLine=line.split(" ");        String first=splitLine[0];        String second=splitLine[1];        Double third=Double.parseDouble(splitLine[3]);       Student stu=            new Student(first,second));        list.add(stu);    }  ......   return list;}
查看完整描述

2 回答

?
HUX布斯

TA貢獻1876條經驗 獲得超6個贊

對于您的問題 (1)


Student s = new Student(first + " " + second, third);

//by the way for third,it is not splitLine[3],it is splitLine[2]

對于您的問題 (2)


ArrayList<Student> studentList = readStudent("YourFileName");

for(Student s : studentList)

    System.out.println(s.name + " " + s.grade);//don't know what are the variable names of Student class instances


查看完整回答
反對 回復 2022-09-22
?
桃花長相依

TA貢獻1860條經驗 獲得超8個贊

您在代碼中有不同的選擇://問題1(請參閱上面的第一條評論):

如果您出于任何原因不需要第一,第二和第三,請選擇選項1(這是有效的)。


public static ArrayList<Student> readStudent(String fName) throws FileNotFoundException, IOException{


        ArrayList<Student> list=new ArrayList<Student>();

        //try{


        BufferedReader br=new BufferedReader(new FileReader(fName));


        String line;


        while((line=br.readLine())!=null){


            //option1

            String[] splitLine=line.split(" ");

            Student stu = new Student(splitLine[0] + " " + splitLine[1], splitLine[2]);


            //option2

//            String first=splitLine[0];

//            String second=splitLine[1];

//            double third=Double.parseDouble(splitLine[3]);            

//            Student stu = new Student(first + " " + second, third); 



            list.add(stu);



        }


        //......


        return list;

    }

問題 2:

在 Java 中,獲取器和設置器用于訪問類的屬性(它是首選樣式)。檢查是否有一些在課堂上的學生,然后使用它。

在選項 2 中,您可以訪問學生對象的方向全局變量。


printStudents(readStudent("your file name"));     //print a list of student objects 


void printStudents(List<Student> students){

    for(Student stu: students)

        //option 1: using getter

        System.out.println(stu.getSStudent()+"  "+stu.getMark());


        //option 2: accessing attributes 

        //System.out.println(stu.sstudent+"  "+stu.mark);

}


查看完整回答
反對 回復 2022-09-22
  • 2 回答
  • 0 關注
  • 94 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號