所以我试图做一个金字塔的增值。防爆。第1行有(5),第2行有(6,7)第3行有(12,10,7)。目标是添加第一行的最高值,以及下一行的最高连接子值。因此,在这种情况下,您将添加5 + 7 + 10,结果为22.您不能在第3行中使用12的原因是因为您必须使用上述数字的子女(每位家长都有2个孩子)。Java扫描仪/阵列金字塔
我的方法是使用扫描仪转变为int值加载到一个数组行由行,不知何故指数前行的最高孩子值的位置,将其添加到正在运行的总。下面的代码我到目前为止...
//数据文件...
//这一切。
public static void main(String[] args) {
Scanner scanner = null;
try {
scanner = new Scanner(new File("https://stackoverflow.com/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个职位]
我怎样才能让扫描器读取一行,它加载到一个数组,循环,并保存从下一行的阵列最高孩子的价值?
哦,我知道这是搞砸了,if/else甚至都不起作用,但我会做出修复,谢谢! –