Java扫描器/阵列金字塔
所以我想把附加值做成一个金字塔。例如,1号线有(5),2号线有(6,7),3号线有(12,10,7)。目标是将第一行的最高值与下一行的最高连接子值相加。在这种情况下,你可以加上5+7+10,得到22的结果。第3行中不能使用12的原因是,您必须使用上述数字的子项(每个父项有2个子项)
我的方法是使用Scanner逐行将int值加载到数组中,并以某种方式索引上一行的最高子值的位置,将其添加到运行总数中。这是我到目前为止的代码
//在数据文件中
五,
6 7
12107
//就这些
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,…最多100个位置]
五,
如何让扫描仪读取一行,将其加载到数组中,循环该行,并保存下一行数组中的最高子值
# 1 楼答案
当我执行代码时,在读取所有数字后,我得到一个NoTouchElementException。这是因为您总是检查文件的下一行,但读取下一个整数
代码中有太多的逻辑缺陷,所以很难对它们全部进行评论。以下是一些你可以研究的问题:
在循环之外,只需添加一次total+结果。你应该把它移动到一个循环中,这样总数就可以正确计算了
你计算结果不正确。至少,您应该有一个变量来指示最后一行中最高数字的位置。你也在比较i-1和i+1。。。当你进入最后一行时,这将不起作用,因为你将把项目与i的任何一边进行比较,而不是与i下面的项目进行比较
我建议将变量读入一个三角形2D数组。你可以为每一行创建另一个扫描器;将每一行读入新的扫描仪;以及对nextInt()进行轮询。 然后,您可以比较arr[row][pos]和arr[row][pos+1],它们将是arr[row-1][pos]的子代
一旦你可以将文件读入2D数组,并从数组中打印int,使其看起来与文件内容一样,如果你仍然有问题,请回来,我可以给你更多帮助