我有這種方法,當它找到 或 - 的符號時應該切割一個字串(它是導數計算器的一部分,所以想法是得到一堆由 或 - 分隔的小字串,然后將它們派生一個一個。這就是為什么我要搜索左括號和右括號)問題是:當呼叫 res = new String(); 它將創建一個新的 String,但它也會將陣列中所有現有的 String 物件設定為 null,這意味著該方法的回傳將始終是一個陣列,所有內容都設定為 null(除非它找不到 或 -在函式中)。有沒有解決的辦法?
public static String[] cutString(String func)
{
int number_strings_res = 0;
int number_parenthesis = 0;
String[] res = new String[1];
res[0] = new String(func);
for(int i = 0; i < func.length(); i )
{
if(func.charAt(i) == ' ' || func.charAt(i) == '-')
{
for(int j = 0; j < i; j )
{
if(func.charAt(j) == '(')
number_parenthesis ;
if(func.charAt(j) == ')')
number_parenthesis--;
}
if(number_parenthesis == 0)
{
res[number_strings_res] = "";
for(int j = 0; j < i; j )
{
res[number_strings_res] = func.charAt(j);
}
number_strings_res ;
res = new String[number_strings_res 1];
res[number_strings_res] = new String(Character.toString(func.charAt(i)));
number_strings_res ;
res = new String[number_strings_res 1];
res[number_strings_res] = new String();
}
}
}
return res;
}
uj5u.com熱心網友回復:
res = new String[number_strings_res 1]分配一個新陣列并將其存盤到res. 這就是當前問題的根源。如果您不知道集合將持續多長時間,您可能應該使用List, like 。ArrayList
uj5u.com熱心網友回復:
當呼叫 res = new String() ...
你沒有這樣的電話,它無論如何也不會編譯。
'res' 被宣告為參考字串陣列的變數。當您執行時,res = new String[...]您自然會替換整個字串陣列。
但我真的無法弄清楚你的意圖是什么?你想擴展陣列嗎?你不能,直接。
如果必須使用陣列,請查看Arrays.copyFrom. 但是 ArrayList 會更容易。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/447654.html
上一篇:如何以另一種方法訪問物件?
