我目前正在研究一個涉及創建一個對象數組的項目(在這種情況下,創建的ToolItem
類中的硬件工具),然後創建一個類文件操縱這些數據。我現在創建的類名爲HardwareStore
,它具有搜索,插入和刪除數組中項目的私有數據成員的方法。使用前面提到的ToolItem
類中名爲assign()
的方法,我爲每個數據成員調用set方法,並將它們分配給數組中的一個點。分配是這樣的:試圖瞭解true/false格式的設置方法的數據驗證
public void assign(int quality, String name, int id, int numInStock, double price)
{
setQuality(quality);
setToolName(name);
setID(id);
setNumberInStock(numInStock);
setPrice(price);
}
我的插入方法目前的樣子:
public int insert(int quality, String name, int id, int numInStock, double price)
{
//testing the unique ID passed by the user,
//making sure there isn't an object in the
//array with the same ID
testArray = searchArray(id);
//array holds a max of 10 objects
if (numberOfItems == 10)
{
System.out.println("Array is full");
return 0;
}
//-1 is sentinel value from search method,
//telling me there isn't an object with the
//same specified ID
else if (testArray == -1)
{
for (index = 0; index < toolArray.length; index++)
{
if (toolArray[index].getToolID() == 0)
{
toolArray[index].assign(quality, name, id, numInStock, price);
numberOfItems++; //counter for array
return 1;
}
}//end for loop
}
return -1; //sentinel value telling me there was a dupe ID
}//end insert
我應該以這種方式使用一個布爾變量來驗證toolArray[index].assign(quality, name, id, numInStock, price);
,雖然:
boolean oK = toolArray[index].assign(quality, id, numInStock, price);
如果oK == true
,然後我增加數組中的項目數。爲了這個工作,我需要assign()
返回類型boolean
。這是如何解釋給我的:
是的,你會想要一個Assign方法。進入它的所有內容都是「設定」值到指定地點的呼叫。 assign方法將返回一個值,取決於值是否被賦值/插入。您需要檢查oK的值以確保其爲真或假。
我的問題是,我不知道如何將assign()
返回類型更改爲boolean
並使該方法正常工作。我首先想到的是這樣的:
if (setQuality(quality) == true)
{
return true;
}
else if (setToolName(name) == true)
{
return true;
}
else
return false;
但這顯然並不在幾個編譯器錯誤工作和結果:/我只是不理解這種數據檢查背後的邏輯。如果有人瞭解這一點,並可以幫助我,我將不勝感激!
感謝nem的快速反應!我即將快速測試它,看看它是否有效,但它絕對看起來應該是這樣!我的設置方法有自己的自定義異常(至少我認爲他們確實基於你說的)。例如,如果質量數據成員不在1和3之間,則將其設置爲0等。這是我的指示,雖然我喜歡你的方式更好:) – FuegoJohnson 2014-09-29 00:12:13
@FuegoJohnson歡迎您:)。讓我知道如果你卡住 – nem035 2014-09-29 00:20:08
非常感謝!在這個網站上需要更多像你一樣的人 – FuegoJohnson 2014-09-29 00:26:25