努力寻找从一个列表中的最后一个的第n个元素(与文件输入) [英] Trying to find the nth element to the last from a list (with a file input)

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

问题描述

输入看起来像

a b c d 4
e f g h 2

,其中每一行被读等作为在列表中的索引列表,并且整数重新presenting

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

我第一次尝试读取文件中的行是行,并将其存储在列表中。继承人我有什么

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);

前面有人给我提供了这片code的,我尝试过了,它在抛出的String []元素NullPointerException异常。

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

推荐答案

这是因为你正在运行,直到行是空此处

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

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

    }

然后你试图调用 .trim()就可以了。

你的意思是在被处理字符串列表呢?

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

如果这样尝试循环遍历你列出,你已经在正确的分裂,并获得最后一个元素。所有你需要做的是caluclate的偏移量,在这种情况下,这将是长度 - 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天全站免登陆