所以我試圖做一個金字塔的增值。防爆。第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甚至都不起作用,但我會做出修復,謝謝! –