java - 尝试从列表中查找倒数第 n 个元素(使用文件输入)

标签 java list file-io arraylist

输入看起来像

a b c d 4
e f g h 2

其中每一行都会像列表一样被读取,整数表示为列表中的索引

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

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 的输入。

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[] 元素处抛出了一个空指针异常。

最佳答案

这是因为你正在运行直到这里的行为空

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

    }

然后您尝试对其调用 .trim()

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

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

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

关于java - 尝试从列表中查找倒数第 n 个元素(使用文件输入),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21612168/

相关文章:

javascript - 使用 Angular 将项目添加到列表顶部

java.io.FileNotFoundException : the system cannot find the file specified

java - 将 2 个日期与一种格式结合起来?

java - 在 Eclipse 插件的菜单中创建一个单选按钮

list - 根据字段子集的列表中的唯一元素

python - 如果我在脚本仍在执行文件 I/O 操作时突然关闭脚本,会发生什么情况?

javascript - filesaver.js 不适用于 cordova 应用程序

java - 单独的类/方法中的方法实例?

java - 格式化程序错误和问题

c# - 从字符串列表中添加和删除项目,仅在项目不存在时添加