【发布时间】:2018-04-03 06:20:45
【问题描述】:
您好,我正在编写一个将字符串解析为单个组件的程序,但是当我尝试对其进行测试时,出现内存不足错误。我觉得我的 for/while 循环似乎是无限的,但我似乎找不到原因。
//for loop to loop through char of string
for(int i=0; i<expressionString.length(); i++) {
//cast char into ascii int
int ascii = (int) charAt(i);
//appending to token if one of singly operator symbols: *,/,(,),[,]
if(ascii == 40 || ascii == 41 || ascii == 42 || ascii == 47 || ascii == 91 || ascii == 93){
token.append((char) ascii);
tokenList.add(token.toString());
} //append if +, -
else if(ascii == 43 || ascii == 45) {
token.append((char) ascii);
//check next char if + or /, if so append to token again
int nextChar = (char) charAt(i+1);
if(nextChar == 43 || nextChar == 45) {
token.append((char) nextChar);
}
tokenList.add(token.toString());
} //appending to token if it's a num
else if ( ascii >= 48 || ascii <=57) {
token.append((char) ascii);
//check if next char is a num
while ((int) charAt(i+1) >= 48 || (int) charAt(i+1) <= 57) {
//increment i in for loop to check
i++;
token.append((int) charAt(i));
}
tokenList.add(token.toString());
}
//
}
如果这是我的代码错误,请告诉我,因为我似乎无法找出问题所在。谢谢!
【问题讨论】:
-
第 51 行是什么?这似乎是发生异常的地方。另外:我认为您在这里需要
&&而不是||。( ascii >= 48 || ascii <=57) -
旁白:如果您只是在条件中使用
ascii == '*'等(或"*/()[]".indexOf((char) ascii) >= 0),则无需评论“*,/,(,),[,]”。 -
如果@MFisherKDX 的提示不能帮助提供全班请。
-
你永远附加到
token的末尾,永远不会从中删除。您打算这样做,还是应该在tokenList.add调用后删除其内容? -
tokenList是一个数组列表,我正在尝试将每个token分别附加到数组列表中。我不确定我是否理解您删除其内容的意思——我为什么需要删除它?如果您可以详细说明,@AndyTurner
标签: java eclipse memory-leaks out-of-memory