【发布时间】:2013-12-16 20:06:53
【问题描述】:
我正在尝试创建一个方法来检查 userInput 中的每个字符以查看它们是否存在于 operatorAndOperands 中。问题是 tempbool 对于所有值始终为 false。
import java.util.*;
public class stringCalculator
{
private String userInput = null;
String[] operatorsAndOperands = {"1","2","3","4","5","6","7","8","9","0","+","-","*","/"};
public stringCalculator(String newInput)
{
userInput = newInput;
}
public boolean checkInput()
{
boolean ifExists = true;
for(int i=0; i<userInput.length(); i++)
{
char currentChar = userInput.charAt(i);
boolean tempbool = Arrays.asList(operatorsAndOperands).contains(currentChar);
if (tempbool == false)
{
ifExists = false;
}
}
return ifExists;
}
}
【问题讨论】:
-
currentChar 的数据类型是
char,你的操作数的数据类型是Strings。tempbool永远是假的。 -
operatorsAndOperands 是一个字符串数组,你正在与循环中的一个字符进行比较
-
另请注意,您可以在 if 语句中
break;您的循环(无需检查其他字符是否有效,因为您找到了一个无效字符)。
标签: java arrays string character