Home > Software design >  Add to all Strings in an arraylist different letters
Add to all Strings in an arraylist different letters

Time:12-12

I have an issue I know I can solve just using an array but that makes a later part of the program more challenging. Im reading off of a datafile a bunch of letters spaced out. i want to sort them into columns, the data file shows this:

[J]             [F] [M]            
[Z] [F]     [G] [Q] [F]            
[G] [P]     [H] [Z] [S] [Q]        
[V] [W] [Z] [P] [D] [G] [P]        
[T] [D] [S] [Z] [N] [W] [B] [N]    
[D] [M] [R] [J] [J] [P] [V] [P] [J]
[B] [R] [C] [T] [C] [V] [C] [B] [P]
[N] [S] [V] [R] [T] [N] [G] [Z] [W] 

I keep on getting an error on line 18. "

   java -classpath .:target/dependency/* Main
[J]             [F] [M]            
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index 0 out of bounds for length 0
    at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:64)
    at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Preconditions.java:70)
    at java.base/jdk.internal.util.Preconditions.checkIndex(Preconditions.java:266)
    at java.base/java.util.Objects.checkIndex(Objects.java:359)
    at java.base/java.util.ArrayList.get(ArrayList.java:427)
    at Main.main(Main.java:18)
1 import java.util.*;
2 import java.io.*;
3 public class Main {
4 public static void main(String [] args) throws FileNotFoundException{
5    String line; 
6    ArrayList<String> C = new ArrayList<>();
7    String a = "";
8    Scanner input = new Scanner(new File("dat.dat"));
9    while (input.hasNextLine()) {
10        line = input.nextLine();
11      if (line.indexOf("[") != -1)
12      {
13        System.out.println(line);
14        a = "";
15        for(int lcv = 1; lcv < line.length() - 1; lcv = 4)
16          {
17            a = line.substring(lcv, lcv 1);
18            C.set(lcv/4, C.get(lcv/4)   a);
19          }
20      }
21      }

how would i go about doing this? I don't want to use a regular array because i'm going to be shuffling these strings around later on.

Expected output: the list will look like

JZGVTDBN
 FPWDMRS
   ZSRCV
 GHPZJTR
FQZDNJCT
MFSGWPVN
  QPBVCG
    NPBZ
     JPW

CodePudding user response:

You're trying to modify the existing element in your ArrayList instead of adding a new element. That's why you're getting the error on line 18.

First, you must add the element in the ArrayList and then you can update it at the index you want.

Also, you can initialize your ArrayList by adding empty elements based on the length of line.

C.add(a);
C.set((lcv / 4), C.get((lcv / 4))   a);

Your end result should look something like this:

import java.util.*;
import java.io.*;

public class Main {
    public static void main(String [] args) throws FileNotFoundException{
        String line; 
        ArrayList<String> C = new ArrayList<>();
        String a = "";
        Scanner input = new Scanner(new File("dat.dat"));

        while (input.hasNextLine()) {
            line = input.nextLine();
            if (line.indexOf("[") != -1) {
                System.out.println(line);
                a = "";

                // Init the ArrayList
                for (int i = 0; i < line.length() / 4; i  ) {
                    C.add("");
                }

                for(int lcv = 1; lcv < line.length() - 1; lcv = 4) {
                    a = line.substring(lcv, lcv 1);
                    // Add the new element into the ArrayList
                    // and update it later
                    C.add(a);
                    C.set((lcv / 4), C.get((lcv / 4))   a);
                }
            }
        }
    }
}

CodePudding user response:

One alternative would be to use a Map. Then you can use Map.compute to build the column strings.

List<String> list = readFile("dat.dat");
list.forEach(System.out::println);

prints

[J]             [F] [M]            
[Z] [F]     [G] [Q] [F]            
[G] [P]     [H] [Z] [S] [Q]        
[V] [W] [Z] [P] [D] [G] [P]        
[T] [D] [S] [Z] [N] [W] [B] [N]    
[D] [M] [R] [J] [J] [P] [V] [P] [J]
[B] [R] [C] [T] [C] [V] [C] [B] [P]
[N] [S] [V] [R] [T] [N] [G] [Z] [W] 
JZGVTDBN
 FPWDMRS
   ZSRCV
 GHPZJTR
FQZDNJCT
MFSGWPVN
  QPBVCG
    NPBZ
     JPW

Method to process input file and return List of strings.

public static List<String> readFile(String file) {

    Map<Integer, String> columnMap = new LinkedHashMap<>();

    try {
        Stream<String> stream = Files.lines(Path.of(file));
        stream.forEach(line -> {
            if (line.indexOf("[") != -1) {
                System.out.println(line);

                for (int lcv = 1; lcv < line.length() - 1; lcv  = 4) {
                    String letter = line.substring(lcv, lcv   1);
                    columnMap.compute(lcv / 4,
                        (k, v) -> v == null ? letter // init to letter if null
                                : v.concat(letter)); // else append letter
                }
            }
        });

    } catch (IOException ioe) {
        ioe.printStackTrace();
    }
    return new ArrayList<>(columnMap.values());
}
  • Related