如何将值复制到对象数组

时间:2017-10-13 08:10:00

标签: java arrays

我创建了一个包含几个对象的类。

S0001
Alice
2000
S0002
Bob
3400
S0003
Cindy
1200
S0004
Dave
2600


所以现在我需要将一些数据从文本文件复制到数组中。

“sales.txt”

class ArrayImport {
    public static void main(String args[]) throws FileNotFoundException {
        String fileName = "sales.txt";
        SalesPerson sp = new SalesPerson[4]; //Manually counted

        //Read the file
        Scanner sc = new Scanner(new FileReader(fileName));

        //Copy data to array
        int i = 0;
        while (sc.hasNext()) {
            sp[i].name = sc.nextLine(); //Error starts here
            sp[i].number = sc.nextLine();
            sp[i].salesAmount = Double.parseDouble(sc.nextLine());
            i++;
        }
    }
}


下面是我的代码的缩短版本,假设创建了getName(s),setName(s)和构造函数,并且可以成功读取文本文件:

{{1}}

我收到错误消息“线程中的异常”main“java.lang.NullPointerException ...”指向我评论的“Error starts here”。


所以我猜这不是为对象数组赋值的方法,如果我的猜测是正确的,那么正确的语法是什么?

2 个答案:

答案 0 :(得分:0)

object的实例为null,因此您必须先创建实例。所以创建这样的实例' staff [i] = new SalesPerson();' 我在您的代码中添加了实例创建。

  class ArrayImport {
    public static void main(String args[]) throws FileNotFoundException {
        String fileName = "sales.txt";
        SalesPerson sp = new SalesPerson[4]; //Manually counted

        //Read the file
        Scanner sc = new Scanner(new FileReader(fileName));

        //Copy data to array
        int i = 0;
        while (sc.hasNext()) {
            staff[i] = new SalesPerson();
            staff[i].name = sc.nextLine(); //Error starts here
            staff[i].number = sc.nextLine();
            staff[i].salesAmount = Double.parseDouble(sc.nextLine());
            i++;
        }
    }
}

答案 1 :(得分:0)

工作示例:

public class ArrayImport {

        public static void main(String[] args) throws FileNotFoundException {
            List<SalesPerson> persons = new ArrayList<>();
            SalesPerson salesPerson = null; //Manually counted

            //Read the file
            Scanner scanner = new Scanner(new FileReader("sales.txt"));

            int count=0;
            while(scanner.hasNext()) {
                if( count==0 || count%3 == 0) {
                    salesPerson = new SalesPerson();
                    salesPerson.setNumber(scanner.nextLine());
                    salesPerson.setName(scanner.nextLine());
                    salesPerson.setSalesAmount(Double.parseDouble(scanner.nextLine()));
                    persons.add(salesPerson);
                    count+=3;
                }
            }
            persons.forEach(person->System.out.println(person.toString()));
        }
    }