在Java中的我自學的數量最多,我想從每個2個陣列獲得數量最多的充分利用各2列
我不知道爲什麼下面的輸出被執行:
Largest: 3
Largest: 8
Largest: 9
Largest: 23
Largest: 33
Largest: 41
Largest: 51
正確的輸出應該是:
Largest: 23
Largest: 51
下面的代碼如何能得到最多?因爲(getLargest1[i] > largest)
等於getLargest1[i] > 0
,其中largest = 0
。
爲什麼要largest = getLargest1[i];
?
public class MyProgram
{
public void start()
{
int[] getLargest1 = {3, 8, 4, 9, 5, 5, 23, 14};
int[] getLargest2 = {33, 23, 41, 9, 17, 51, 23, 45};
getLargestFunc(getLargest1, getLargest2);
}
private void getLargestFunc(int[] getLargest1, int[] getLargest2)
{
int largest = 0;
for (int i = 0; i < getLargest1.length; i++)
{
if (getLargest1[i] > largest)
{
largest = getLargest1[i];
System.out.println("Largest: " + largest);
}
}
for (int i = 0; i < getLargest2.length; i++)
{
if (getLargest2[i] > largest)
{
largest = getLargest2[i];
System.out.println("Largest: " + largest);
}
}
}
}
將您的'print' stmt移到for循環之外。 – Ambrish
在for循環後移動每個打印語句,並且在第一個循環後將「最大」變量重置爲「0」# – BackSlash
@ BackSlash或每個陣列的第一個元素 –