扫描文本文件导入对象数组 [英] Scanning text file into array of objects

查看:160
本文介绍了扫描文本文件导入对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有格式信息的逗号分隔文本文件:

名字,姓氏,meal1,meal2,meal3,meal4 ....对每个新行一个新来的学生。

我有以下的学生对象。

 公共类学生{
    私人字符串第一个= NULL;
    私人字符串最后= NULL;    公共学生(第一字符串,字符串最后一个){
        this.first =第一;
        this.last =最后;
    }

我需要的是从另一个类用于填充学生对象的数组的方法。

我不能确定如何使用扫描仪做到这一点,因为我只需要前两个来自每一行,任何指着我的方向是正确的帮助将非常感激。

〜谢谢!


解决方案

  {尝试
        档案文件=新的文件(input.txt的);
        扫描仪扫描=新的扫描仪(文件);        而(scanner.hasNextLine()){
            串行= scanner.nextLine();
            String数组[] = line.split();
            学生学生=新的学生(数组[0]数组[1]);
            -------------------------
            -------------------------
            的System.out.println(姓:+阵列[0]);
            的System.out.println(名字:+阵列[1]);
        }
        scanner.close();
    }赶上(FileNotFoundException异常五){
        e.printStackTrace();
    }

I have a comma separated text file with information in the format:

firstname,lastname,meal1,meal2,meal3,meal4 ....with each new student on a new line.

I have the following student object.

public class Student {
    private String first = null;
    private String last = null;

    public Student (String first, String last){
        this.first = first;
        this.last = last;
    }

I need a method that is to be used from another class to populate an Array of student objects.

I am unsure how to do this with the Scanner as I only need the first two from each line, any help pointing me in the right direction would be very thankful.

~Thanks!

解决方案

  try {
        File file = new File("input.txt");
        Scanner scanner = new Scanner(file);

        while (scanner.hasNextLine()) {                
            String line = scanner.nextLine();
            String array[] = line.split(",");
            Student student  = new Student (array[0],array[1]);
            -------------------------
            -------------------------
            System.out.println("FirstName:"+ array[0]);
            System.out.println("LastName:"+ array[1]);
        }
        scanner.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

这篇关于扫描文本文件导入对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆