Skip to content
Advertisement

Splitting a text file into two parallel arrays (java)

I have a file that’s a translation of morse code patterns into the alphabet.

I need to separate this file into keys and values, in two separate arrays.

I am hoping someone can show me the basic algorithm that would generate a similar result so I can model my code after it.

How would I split the left section into it’s own array as well as the right section into its own array? [1]: https://i.stack.imgur.com/X3i99.png

Advertisement

Answer

Read the file in, and then go character by character comparing them to an array you construct of possible characters. Construct two other arrays, and if the comparison matches one or the other put the character in the correct array based on the comparison.

// Java program to iterate over an array 
// using for loop 
import java.io.*; 
class GFG { 
  
    public static void main(String args[]) throws IOException 
    { 
        int ar[] = { 1, 2, 3, 4, 5, 6, 7, 8 }; 
        int i, x; 
  
        // iterating over an array 
        for (i = 0; i < ar.length; i++) { 
  
            // accessing each element of array 
            x = ar[i]; 
            System.out.print(x + " "); 
        } 
    } 
} 

Reading files something like

import java.io.File;  // Import the File class
import java.io.FileNotFoundException;  // Import this class to handle errors
import java.util.Scanner; // Import the Scanner class to read text files

public class ReadFile {
  public static void main(String[] args) {
    try {
      File myObj = new File("filename.txt");
      Scanner myReader = new Scanner(myObj);
      while (myReader.hasNextLine()) {
        String data = myReader.nextLine();
        System.out.println(data);
      }
      myReader.close();
    } catch (FileNotFoundException e) {
      System.out.println("An error occurred.");
      e.printStackTrace();
    }
  }
}
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement