【问题标题】:Splitting a text file into two parallel arrays (java)将文本文件拆分为两个并行数组(java)
【发布时间】:2020-11-27 02:54:00
【问题描述】:

我有一个将莫尔斯电码模式翻译成字母表的文件。

我需要将此文件分成键和值,放在两个单独的数组中。

我希望有人可以向我展示会产生类似结果的基本算法,以便我可以根据它对我的代码进行建模。

如何将左侧部分拆分为它自己的数组以及 正确的部分放入自己的数组中? [1]: https://i.stack.imgur.com/X3i99.png

【问题讨论】:

    标签: javascript arrays algorithm file-io split


    【解决方案1】:

    读入文件,然后逐个字符地将它们与您构造的可能字符的数组进行比较。构造另外两个数组,如果比较匹配一个或另一个,则根据比较将字符放入正确的数组中。

    // 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 + " "); 
            } 
        } 
    } 
    
    

    读取文件之类的

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

    【讨论】:

    • 我将如何逐个字符进行?
    • @yoyo2 扫描仪输出的每一行都是一个字符串,您基本上可以将字符串视为数组。另外,有人对否决票有解释吗?如果有可操作的反馈,我很乐意添加到这个答案中。
    猜你喜欢
    • 2017-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-25
    • 2013-07-23
    • 1970-01-01
    相关资源
    最近更新 更多