试图从列表中找到第 n 个元素到最后一个(使用文件输入) [英] Trying to find the nth element to the last from a list (with a file input)

查看:22
本文介绍了试图从列表中找到第 n 个元素到最后一个(使用文件输入)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

输入看起来像

a b c d 4
e f g h 2

其中每一行将被读取为一个列表和整数表示为列表中的索引

where each line would be read like a list and integer representing as an index in the list

我首先尝试读取文件 line 并将其存储在列表中.这是我所拥有的

I first try to read the file line be line and store it in the list. Heres what i have

public class FileReader {

    public static void main(String[] args) {
        String line = null;
        List<String> list = new ArrayList<String>();

        try {
            FileInputStream fstream = new FileInputStream("test.txt");
            DataInputStream in = new DataInputStream(fstream);
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            // File file = new File("test.txt");
            // Scanner scanner = new Scanner(file);
            while ((line = br.readLine()) != null) {
                list.add(line);
            }

            System.out.println(list);

        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

现在我想从列表中删除空格并将值存储在 char 数组中,然后我计划向后遍历该数组直到第 n 个元素,具体取决于 n 的输入.

Now i want to remove the white spaces from the list and store the values in char array and then i was planning on traversing that array backwards till the nth element, depending on the input for n.

String[] elements = line.trim().split("\\s");
char[] chars = new char[elements.length - 1];
int i= Integer.parseInt(elements[elements.length - 1]);
for (i = 0; i < elements.length - 1; i++)
    char[i] = elements[i].charAt(i);

之前有人给我提供了这段代码,我试了一下,它在 String[] 元素上抛出了一个空指针异常.

Someone provided me this piece of code earlier and i tried it and it throws a nullpointerexception at String[] elements.

推荐答案

这是因为你一直在运行直到这里的 line 为 null

It's because you are running until line is null here

    while((line = br.readLine()) != null)
    {   
            list.add(line);

    }

然后你试图调用 .trim() .

您的意思是要处理 list 中的字符串吗?

Do you mean to be processing the strings in list instead?

如果是这样,请尝试遍历您的列表,您已经正确拆分它并获得最后一个元素.您需要做的就是计算偏移量,在这种情况下,它将是长度 - 1 - 最后一个元素,在您的 String[] 元素中,您可以将其打印出来.

If so try looping over you list, you are already splitting it correctly and getting the last element. All you need to do is caluclate the offset, in this case it will be the length - 1 - the last element, in you String[] elements and you can print that out.

    for (int i = 0; i < list.size(); i++)
    {
        String currentLine = list.get(i);
        String[] elements = currentLine.trim().split("\\s");
        int lastElement = Integer.parseInt(elements[elements.length - 1]);

        String desiredValue = elements[elements.length - 1 - lastElement];
        System.out.println("desiredValue = " + desiredValue);
    }

这篇关于试图从列表中找到第 n 个元素到最后一个(使用文件输入)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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