简体   繁体   English

为什么.size()在此ArrayList上无法正常工作?

[英]Why doesn't .size() work properly on this ArrayList?

I've imported a dat file into an ArrayList. 我已经将dat文件导入到ArrayList中。 My issue is that, although it prints out all the names in the file, it won't give me the correct size. 我的问题是,尽管它会打印出文件中的所有名称,但不会给我正确的大小。 Instead, it just prints out 1. 相反,它只是打印出1。

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;

public class TestArray {
    public static void main (String [] args){
    String filePath = "C:\\Users\\Admin\\workspace\\Fund III\\src\\names.dat";

    Scanner sc = null;
    try {

        sc = new Scanner(new File (filePath ));
    } catch (FileNotFoundException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    //Makes Array list
    ArrayList<String> nameList = new ArrayList<String>();

    //Dumps names into array
try{
    while(sc.hasNextLine())
    {
        nameList.add(sc.nextLine());
    }
   }
    catch(Exception e)
    {
        System.out.println("Error: " + e);
    }
    System.out.println(nameList.size());
    System.out.println(nameList);
}
}

It appears that your file has only one line. 您的文件似乎只有一行。 Here is how to check: 这是检查方法:

while(sc.hasNextLine()) {
    String line = sc.nextLine();
    nameList.add(line);
    System.out.println("Line: '"+line+"'");
}

Run your modified program, and watch for single quotes around your strings. 运行修改后的程序,并注意字符串周围的单引号。 If your output produces multiple lines inside a single pair of quotes, the issue is that your input does not have end-of-line markers expected by the system on which you run your program. 如果您的输出在单引号对内产生多行,则问题在于您的输入没有运行程序的系统所期望的行尾标记。

According to Scanner java doc ... 根据扫描仪的 Java文档...

The default whitespace delimiter used by a scanner is as recognized by Character.isWhitespace . 扫描仪使用的默认空格分隔符由Character.isWhitespace识别。

Are you sure you understand the content of the file and how it has been created (Linux/Windows). 您确定您了解文件的内容以及如何创建文件(Linux / Windows)。

For example when running a Java process on Linux and reading a file that has been created on Windows, I often have to use the dos2unix command to correct the file format, otherwise it won't process as expected unless you put extra effort into specifying the correct file encoding in your java code. 例如,当在Linux上运行Java进程并读取在Windows上创建的文件时,我经常不得不使用dos2unix命令来更正文件格式,否则除非您付出额外的精力来指定文件名,否则它将无法按预期进行处理。 Java代码中正确的文件编码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM