Java扫描程序/数组金字塔

时间:2012-07-04 01:26:07

标签: java arrays loops io

所以我试图建立一个增值的金字塔。防爆。第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

如何让扫描仪读取一行,将其加载到一个数组中,然后将其循环,然后从下一行的数组中保存最高的子值?

1 个答案:

答案 0 :(得分:0)

当我执行该代码时,我在读完所有数字后得到NoSuchElementException。发生这种情况是因为您总是检查文件的下一行,但是要读取下一个整数。

代码中存在很多逻辑缺陷,很难对它们发表评论。以下是您可以使用的一些内容:

您只需在循环外添加总计+结果ONCE。你应该在循环中移动它,以便正确计算总数

您错误地计算结果。至少,你应该有一个变量来指示最后一行中最高数字的位置。您还将i -1与i + 1进行比较......当您进入最后一行时,这将无效,因为您将比较i的任何一侧而不是i之下的项目。

我建议将变量读入三角形2D数组。您可以通过为每行创建另一个扫描程序来完成此操作;将每一行读入新扫描仪;和轮询nextInt()。 然后,这可以让你比较arr [row] [pos]和arr [row] [pos + 1],这将是arr [row-1] [pos]的孩子。

一旦你可以将文件读入2D数组并从数组中打印出来看起来就像文件内容一样,如果你仍然遇到麻烦,那就回来吧,我可以给你一些帮助。