java数组: split elements

标签 java arrays

我有一个程序,它将从文件中读取并将文件的每一行添加为数组的元素。我现在想做的是弄清楚如何编辑数组中的某些项目。

问题是我的输入文件看起来像这样

number of array items
id, artist name, date, location
id, artist name, date, location

例如

2
34, jon smith, 1990, Seattle
21, jane doe, 1945, Tampa

因此,如果我调用 artArray[0] 我会得到 34, jon smith, 1990, Seattle 但我正在尝试弄清楚如何更新 Seattle 当输入 34 的 id 时,是否可以用逗号分隔数组中的每个元素?或者使用多维数组代替?

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

public class ArtworkManagement {

    /**
     * @param args
     */
    public static void main(String[] args) {
        String arraySize;

        try {
            String filename = "artwork.txt";
            File file = new File(filename);         
            Scanner sc = new Scanner(file);

            // gets the size of the array from the first line of the file, removes white space.
            arraySize = sc.nextLine().trim();
            int size = Integer.parseInt(arraySize);  // converts String to Integer.
            Object[] artArray = new Object[size];    // creates an array with the size set from the input file.

            System.out.println("first line: " + size);

            for (int i = 0; i < artArray.length; i++) {
                 String line = sc.nextLine().trim();
//               line.split(",");
                 artArray[i] = line;
            }

            System.out.println(artArray[0]);

            sc.close();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


    }
}

最佳答案

你就快到了,但是split返回一个数组,因此您需要一个数组的数组。

您可以更改此行

Object[] artArray = new Object[size];

通过这个,您还可以使用 String 而不是 Object,因为这确实是一个字符串。

String[][] artArray = new Object[size][];

然后你可以将数组添加到数组的数组中

artArray[i] = line.split();

最后使用两个索引访问它:

artArray[indexOfTheArray][indexOfTheWord]

此外,如果您想打印数组,请使用:

System.out.println(Arrays.toString(artArray[0]));

关于java数组: split elements,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49306939/

相关文章:

java - 在Android/java中求解两个方程组

java - 注入(inject)依赖失败

java - Android 如何使用使用。回收者 View

javascript - 将对象作为数组的数组进行垃圾收集

c - 当我尝试在结构体数组中给出值时,为什么我的程序会停止?

java - 调用获取 XML 元素返回 null

java - PrimeFaces Dock 图标问题

javascript - 为什么json文件最后要加31

C 多维数组,看不出有什么问题

c++ - 丑陋的数字UVA