【问题标题】:Read text file and convert to 2d int array depending on input in Java读取文本文件并根据 Java 中的输入转换为 2d int 数组
【发布时间】:2016-07-17 14:14:34
【问题描述】:

我阅读了一个如下所示的文本文件:

operationName1 Value

行数不定,有不同的操作和对应的值。我可以读取文件并获得一个二维字符串数组作为输出。这是我的代码。

try{
    Path path = Paths.get("./myFile.txt");
    String[][] array = Files.lines(path)
                .map(s -> s.split("\\s+", 2))
                .map(a -> new String[]{a[0], a[1]})
                .toArray(String[][]::new);
    }catch(IOException e){  
}

问题:如何更改我的代码以获取 2d int 数组,其中 operationName1 为“0”而 operationName2 为“1”(只有两个可能的操作,每个操作由特定字符串定义)?

这个文本文件:

operationOne 5
OtherOp 999
operationOne 8
operationOne 2

会变成那个 2d int 数组:

[[0,5],[1,999],[0,8],[0,2]]

索引也很重要。所以文本文件的第一行是我数组的第一行。

PS:如果有更好的语法(更新的),我愿意提出建议。

非常感谢。

【问题讨论】:

  • 嘿大卫,为什么不使用上一个问题的答案并自定义它?
  • 您拥有a[0] 中的值。测试这个值是什么并将其映射到相应的数字 0 或 1。
  • 你为什么要在这里使用流?你打算使用并行性吗?如果不是,那么简单的循环可能会更具可读性(并且可能会快一点)。

标签: java arrays file java-8


【解决方案1】:

我通常使用 Scanner 类来读取文本文件

ArrayList<String[]> array = new ArrayList();
Scanner scan= new Scanner(new File("./myFile.txt"));
String str;
String auxiliary= new String[2];
while(scan.hasNextLine()){
    str= scan.readLine();
    auxiliary=str.split(" "); // you can use also the \\s
    for(int i=0; i<array.size();i++){
        if(array.get(i)[0].equals(auxiliary[0])){
           String  aux2[]={i,auxiliary[1]};
           break;
        }
   }
   String  aux2[]={array.size,auxiliary[1]};
}

希望对你有帮助。

# 编辑:更正了一些问题

【讨论】:

  • 几个问题:(1)扫描仪在没有更多行时不返回null。它抛出异常。因此,您应该使用while(scan.hasNextLine()) 之类的东西,而不是while(str!=NULL)((2)您可能是指null - Java 区分大小写)。 (3) split 期望字符串 " " 而不是 char ' ' 作为参数。 (改进)大多数情况下,当我们有 Scanner 时,不需要使用split。如果我们知道每行会出现多少个元素,我们通常在这里使用haveNexthaveNext*Type*(我们只需要使用hasNext() 而不是hasNextLine)。
  • 谢谢。在过去的 3 个月里,我在 C 中努力工作,我交换了一些东西。但我已经修好了。
【解决方案2】:

它有点长,但它允许你去 operationName1...operationNameN

我总是尽量保持代码干净,所以如果您有任何问题,请尽管提出

public class Main {

    public static void main(String[] args) throws IOException {

            File file = new File("test.txt");
            BufferedReader bufferedReader = new BufferedReader(new FileReader(file));

            ArrayList<String> operations = new ArrayList<String>();
            ArrayList<Point> points = new ArrayList<Point>();

            String line;
            String[] array;

            int index;
            while((line = bufferedReader.readLine()) != null)
            {
                array = line.split(" ");

                if((index = hasOperation(array[0], operations)) == -1)
                {
                    operations.add(array[0]);
                    index = operations.size()-1;
                    points.add(new Point(index, Integer.parseInt(array[1])));
                }
                else
                {
                    points.add(new Point(index, Integer.parseInt(array[1])));
                }
            }

            System.out.print("[");
            for(int i = 0; i < points.size()-1; i++)
            {
                System.out.print(points.get(i).toString() + ",");
            }
            System.out.println(points.get(points.size()-1).toString()+"]");
    }



    public static int hasOperation(String operation, ArrayList<String> operations ){

        for(int index = 0; index < operations.size(); index++)
        {
            if(operation.equalsIgnoreCase(operations.get(index)))
                return index;
        }
        return -1;
    }

}

public class Point {
    public int x;
    public int y;


public Point(int x, int y){
        this.x = x;
        this.y = y;
    }

    @Override
    public String toString()
    {
        return "[" + x + "," + y + "]";
    }
}

【讨论】:

    【解决方案3】:

    如果您需要parallelism? ...这可能是一种方法

    AtomicInteger atomicInteger = new AtomicInteger(0);
    Map<String, Integer> known = new ConcurrentHashMap<>();
    Path path = Paths.get("./myFile.txt");
    int[][] array = Files.lines(path)
        .map(s -> s.split("\\s+", 2))
        .map(a -> new int[]{
            known.computeIfAbsent(a[0],
                    k -> atomicInteger.getAndIncrement()),
            Integer.parseInt(a[1])
        })
        .toArray(int[][]::new);
    

    【讨论】:

    猜你喜欢
    • 2021-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-12
    • 2013-02-06
    • 2016-12-20
    • 1970-01-01
    • 2018-02-27
    相关资源
    最近更新 更多