這更多的只是一個語法錯誤,因爲我的大部分代碼,因爲它是運行完全正常回報指數。問題是,如果在數組中找不到值,我希望程序將其打印出來。如果沒有程序在每行上寫出「未找到」,似乎無法找到編寫代碼部分的地方。以下是我的代碼和控制檯輸出。謝謝大家。搜索一個數組,如果一個特定的值時發現
代碼:
public static void main(String[ ] args)
{
final int[ ] DATA = { 2, 4, 6, 8, 10, 12, 14 };
final int[ ] EMPTY = new int[0];
final int MINIMUM = 0;
final int MAXIMUM = 16;
int target;
System.out.println("Searching for numbers in an array.");
for (target = MINIMUM; target <= MAXIMUM; target++)
{
System.out.print("\nIs " + target + " in the array? ");
{
for (int index = 0; index < DATA.length; index++)
{
if (DATA[index] == target)
System.out.printf("Yes! %d was found at index [%d]", target, index);
}
}
}
控制檯輸出:
Searching for numbers in an array...
Is 0 in the array?
Is 1 in the array?
Is 2 in the array? Yes! 2 was found at index [0]
Is 3 in the array?
Is 4 in the array? Yes! 4 was found at index [1]
Is 5 in the array?
Is 6 in the array? Yes! 6 was found at index [2]
Is 7 in the array?
Is 8 in the array? Yes! 8 was found at index [3]
Is 9 in the array?
Is 10 in the array? Yes! 10 was found at index [4]
Is 11 in the array?
Is 12 in the array? Yes! 12 was found at index [5]
Is 13 in the array?
Is 14 in the array? Yes! 14 was found at index [6]
Is 15 in the array?
Is 16 in the array?
你想你的代碼,這樣做? –
將數組轉換爲ArrayList並使用indexOf()方法不適合您? – n0rph3u5