繁体   English   中英

ArrayList 字符串转换为 ArrayList Integer [暂停]

[英]ArrayList String conversion to ArrayList Integer [on hold]

    ArrayList<String> str = new ArrayList<String>();
    ArrayList<Integer> results = new ArrayList<Integer>();
    File file1 = new File("file3.txt");

    try
    {
        Scanner s = new Scanner(file1);
        s.useDelimiter("\\*-\\*");
        str.add(s.next());
    } catch (FileNotFoundException e)
    {
        System.out.println("File Not Found");
        e.printStackTrace();
    }

    try
    {
        for (String num : str)
        {
            results.add(Integer.parseInt(num));
            System.out.println(results);
        }
    } catch (NumberFormatException nfe)
    {

        System.out.println("Number Format is Not Correct");
        nfe.printStackTrace();
    }           

strStringArrayList

resultsArrayListInteger

我正在尝试将String的 ArrayList 转换为ArrayListInteger但得到NumberFormatException

在 String ArrayList ,我从序列文件中添加元素(数字作为字符串)。

我假设您拥有的是List<String>并且您想将其转换为List<Integer> 我想您已经可以从文件中读取列表,因此我将跳过该部分。

public List<Integer> convertToIntegerList(List<String> inputs) {
    if (inputs == null) {
       return Collections.EMPTY_LIST;
    }
    List<Integer> converted = new LinkedList<>();
    for (String input : inputs) {
        try {
           converted.add(Integer.parseInt(input));
        } catch (NumberFormatException ex) {
           // Note that Integer.parseInt() will throw a NumberFormatException
           // if the argument doesn't represent a valid Integer.
           // How you handle that is on you. For this one we are just going to ignore the invalid number and print it.
           System.out.println("Failed to convert " + input);
           continue;
        }
    }
     return converted;
}

更新:根据更新后的问题,您的文件格式似乎不正确,并且您的inputs包含无效值。 我将首先打印出列表的每个元素并确认它实际上是一个有效的输入(文件读取成功)

更新#2:

有几件事看起来是错误的,但如果没有示例文件,我无法真正说出究竟是什么,只能猜测。 因此,首先您要从正确的文件创建扫描仪。 请注意, Scanner.useDelimiter接受转换为Pattern的字符串作为正则表达式。 您给定的正则表达式\\*-\\*表示您要使用的分隔符实际上是any character followed by a - and followed by any character

我相信你的文件看起来更像这样

 1-2-3-4...

用于该输入的正确分隔符是scanner.useDelimiter("-");

这将拆分-上的输入并返回标记。 现在从您的代码中,您只读取一个令牌,第一个令牌,然后丢弃其他令牌。

我会将其转换为

while (scanner.hasNext()) {
    inputs.add(scanner.next());
}

同样,所有这些都是猜测,添加输入文件将消除混乱。

唯一可能的原因是这一行中的“num”不是表示有效数字的字符串:

results.add(Integer.parseInt(num));

在此行之前尝试 System.out.println(num) 进行仔细检查。 例如:

“123”这是可以解析为数字“123”的字符串,这不是。 你需要删除前导字符

暂无
暂无

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

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