使用扫描仪在java中读取文件时,先前的元素会被最新的元素覆盖,为什么会发生?

时间:2017-12-04 01:59:49

标签: java arrays

File info = new File("..\\userInfo2\\users.txt");
        Scanner size = new Scanner(info);
        Scanner read = new Scanner(info);
        read.useDelimiter(",");
        size.useDelimiter(",");
        
        String ID[], name[], password[];
        int count = 0, sub = 0;
        
        //finds array size
        while(size.hasNext())
        {
            count ++;
            size.next();    //if nextLine(), then # of lines
        }

        name = ID = password = new String [count];
        

for (int i = 0; read.hasNext(); i++) {
    name[i] = read.next();
    read.next();
    ID[i] = read.next();
    password[i]= read.next();
    read.next();
    read.next();

    System.out.println(name[i] + ID[i] + password[i]);
}

name [i]和ID [i]一直被覆盖。最后我总是得到密码[i]三次。为什么会发生这种情况?如何解决?

1 个答案:

答案 0 :(得分:0)

名称,ID和密码是指向同一对象的引用变量。因此,对其中任何一个所做的任何改变都会反映在其他人身上。