random_user_0891
random_user_0891

Reputation: 2071

java array: split elements

I've got a program that will read from a file and add each line of the file as an element of an array. What I'm trying to do now though is to figure out how to edit certain items in the array.

The problem is my input file looks like this

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

so for example

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

so if I call artArray[0] I get 34, jon smith, 1990, Seattle but I'm trying to figure out how to just update Seattle when the id of 34 is entered so maybe split each element in the array by comma's? or use a multidimensional array instead?

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


    }
}

Upvotes: 0

Views: 178

Answers (4)

VHS
VHS

Reputation: 10194

I think you need to use a better data structure to store the file content so that you can process it easily later. Here's my recommendation:

List<String> headers = new ArrayList<>();
List<List<String>> data = new ArrayList<List<String>>();
List<String> lines = Files.lines(Paths.get(file)).collect(Collectors.toList());
//Store the header row in the headers list.
Arrays.stream(lines.stream().findFirst().get().split(",")).forEach(s -> headers.add(s));
//Store the remaining lines as words separated by comma
lines.stream().skip(1).forEach(s -> data.add(Arrays.asList(s.split(","))));

Now if you want to update the city (last column) in the first line (row), all you have to do is:

data.get(0).set(data.get(0) - 1, "Atlanta"); //Replace Seattle with Atlanta

Upvotes: 0

Jay Shankar Gupta
Jay Shankar Gupta

Reputation: 6088

String[][] artArray = new String[size][];    
            System.out.println("first line: " + size);

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

Upvotes: 0

Web.11
Web.11

Reputation: 417

This behavior is explicitly documented in String.split(String regex) (emphasis mine):

This method works as if by invoking the two-argument split method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array.

If you want those trailing empty strings included, you need to use String.split(String regex, int limit) with a negative value for the second parameter (limit):

String[] array = values.split(",", -1);
or
String[] array = values.split(",");

so

 1. array[0] equals to id  
 2. array[1] equals to artist name  
 3. array[2] equals to date 
 4. array[3] equals to location

Upvotes: 0

Jose da Silva Gomes
Jose da Silva Gomes

Reputation: 3974

You are almost there, but split returns an array, so you need an array of arrays.

You can change this line

Object[] artArray = new Object[size];

By this one, you also can use String instead of Object since this is indeed an string.

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

Then you can add the array to the array of arrays with

artArray[i] = line.split();

And finally access to it using two indexes:

artArray[indexOfTheArray][indexOfTheWord]

Also if you want to print the array use:

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

Upvotes: 1

Related Questions