所以我试图建立一个增值金字塔。前任。第 1 行有 (5),第 2 行有 (6,7) 第 3 行有 (12,10,7)。目标是添加第一行的最高值,下一行的最高连接子值。因此,在这种情况下,您将添加 5+7+10,结果为 22。您不能使用第 3 行中的 12 的原因是因为您必须使用上述数字的孩子(每个父母都有2 个孩子)。
我的方法是使用 Scanner 将 int 值逐行加载到数组中,并以某种方式索引前一行的最高子值的位置以将其添加到运行总数中。这是我到目前为止的代码......
//在数据文件中...
5
6 7
12 10 7
//就这样。
    public static void main(String[] args) {
    Scanner scanner = null;
    try {
        scanner = new Scanner(new File("/users/joe/desktop/data.txt"));
    } catch (FileNotFoundException e) {
        System.out.println("File not found.");
        e.printStackTrace();
    } //reads the file
    int[] a = new int[100]; //establishes new array with a max size of 100
    int i = 0; //placeholder for array position
    int result = 0;
    int total = 0;
    while(scanner.hasNextLine()){ //loops through line
        a[i++] = scanner.nextInt(); //adds int to array
        if(i == 0){ //does this belong here?
            result = a[0];
        }
        else{
            if(a[i-1] >= a[i+1]){
                result = a[i-1];
            }
            else if(a[i-1] <= a[i+1]){
                result = a[i+1];
            }
        }
    }
    total =  total + result;
    scanner.close();
    System.out.print(Arrays.toString(a));
    System.out.println("\n" + total);
    }
    }
目前,这将打印出:[5,6,7,12,10,7,0,0,0,0,0,...最多 100 个位置]
5
如何让扫描仪读取一行,将其加载到数组中,循环,并从下一行的数组中保存最高的子值?