我正在制作一个 android 单行计算器。到目前为止,当我用 javascript、c++ 和 c# 编写它时,这个计算器可以工作,但我无法让它在 android (java) 中工作。这是我的代码:
String seq = String.valueOf(sec.getText());
ArrayList<Integer> allNums = new ArrayList<Integer>();
int i = 0;
ArrayList<String> allSigns = new ArrayList<String>();
String currentNums = "";
for (i = 0; i< seq.length(); i++)
{
if (seq.charAt(i) != '+' && seq.charAt(i) != '-' && seq.charAt(i) != '*' && seq.charAt(i) != '/')
{
currentNums+=seq.charAt(i);
}
else
{
allNums.add(Integer.parseInt(currentNums));
currentNums="";
allSigns.add(String.valueOf(seq.charAt(i)));
}
}
allNums.add(Integer.parseInt(currentNums));
int result = (Integer)allNums.get(0);
for (i = 1; i <= allNums.size(); i++)
{
if (allSigns.get(i-1) == "+")
result+=allNums.get(i);
else if (allSigns.get(i-1) == "-")
result-=allNums.get(i);
else if (allSigns.get(i-1) == "*")
result*=allNums.get(i);
else if (allSigns.get(i-1) == "/")
result/=allNums.get(i);
else
{
sec.setText(String.valueOf(result));
break;
}
}
我通过 onClick 事件调用该函数。该应用程序不会崩溃,但只会给我第一个数字作为答案。例如:34+31-4*8/1 它返回 34。有什么想法吗?