這是我有很多代碼,但這裏是我認爲的相關位。創建/返回未知大小int數組
我有一個數組我做大小10作爲存根,我不知道什麼大小的數組我可能會得到,只是它不能大於十。
int[] arrTracker = new int[10];
arrTracker = MyLibrary.SearchForABookISBN(true, AShelf, userParsedArr, aUserTitle);
for (int j = 0; j < 10; j++)
{
pln(AShelf[arrTracker[j]]);
}
在理論上面的代碼中,一旦我有通過它我陣列我環路和顯示內容(這將是基本在在MyLibrary對象數組中有我發現這本書我正在尋找。
「userParsedArr」是用戶輸入ISBN。
public int[] SearchForABookISBN (boolean aFlag, Book[] anArray, int[] AnISBN, String aTitle)
{
//This one was difficult.
int length = anArray.length;
int[] AnotherArr = new int[0];
int[] AnotherArrTemp = new int[0];
int[] AnotherArrNew = new int[0];
boolean UFoundMe = false;
if (aFlag == true)
{
for (int i = 0; i < length; i++)
{
//Assume we find the ISBN
if ((anArray[i].Title.equals(aTitle)))
{
int counter = 0;
for (int j = 0; j < 9; j++)
{
if (anArray[i].ISBN[j] == AnISBN[j])
{
counter++;
}
else
{
UFoundMe = false;
break;
}
if (counter == 9)
{
UFoundMe = true;
}
}
if (UFoundMe == true)
{
//Create our 'main' tracker at 1 + size of previous array.
AnotherArrNew = new int[1 + AnotherArr.length];
if (AnotherArrTemp.length > 0)
{
//Copy values into a temp array.
//Make a new temp array
for (int m = 0; m < AnotherArr.length - 1; m++)
{
AnotherArrNew[m] = AnotherArrTemp[m];
}
}
AnotherArrNew[(AnotherArrNew.length) - 1] = i;
AnotherArrTemp = new int[AnotherArrNew.length];
for (int n = 0; n < AnotherArr.length; n++)
{
AnotherArrTemp[n] = AnotherArrNew[n];
}
System.out.println(anArray[i]);
}
}
}
}
return AnotherArrNew;
}
}
基本這裏的想法是,我創造了一些空白陣列,然後一旦我找到一本書,我創建了一個新的數組一個規模更大,折騰出舊的陣列,將內容傳輸到臨時數組,然後小心地製作一個ba在刪除舊的新陣列以使其變大之前所做的一切。
所以大概說我有10本書,其中3個有相同的標題和ISBN。我希望能夠返回一個3的數組,但是我不知道這件事,因爲如果我給了20本書並且它們都是一樣的呢?
MyLibrary.SearchForABookISBN(true,AShelf,userParsedArr,aUserTitle).length能讓我知道事先獲得的數組大小嗎?所以,只是聲明:
int aLength = MyLibrary.SearchForABookISBN(true, AShelf, userParsedArr, aUserTitle).length
int[] arrTracker = new int[aLength];
如果您事先不知道大小,請使用ArrayList。如果必須,可以將其轉換爲數組。 – jlordo