[英]Android Calculator gives wrong answer
I'm making a android one-line calculator. 我正在制作一个Android单行计算器。 So far this calculator works when I write it in javascript, c++ and c#, but I can't get it to work in android (java).
到目前为止,当我用javascript,c ++和c#编写它时,这个计算器可以工作,但我不能让它在android(java)中工作。 Here is my code:
这是我的代码:
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;
}
}
I'm calling the function by onClick event. 我正在通过onClick事件调用该函数。 The app doesn't crash, but only gives me as answer the first number.
该应用程序不会崩溃,但只给我作为第一个数字的答案。 For example: 34+31-4*8/1 It returns 34. Any Ideas?
例如:34 + 31-4 * 8/1它返回34.任何想法?
You are using the ==
operator to compare string values, which is not correct. 您正在使用
==
运算符来比较字符串值,这是不正确的。 For objects (including Strings), ==
compares the references to determine if they refer to the same object. 对于对象(包括字符串),
==
比较引用以确定它们是否引用同一对象。
To compare string values, use String#equals
instead: 要比较字符串值,请使用
String#equals
:
if ("+".equals(allSigns.get(i-1)))
String comparison in java uses "oneString".equals("another")
not ==
java中的字符串比较使用
"oneString".equals("another")
而不是==
...
if (allSigns.get(i-1).equals("+"))
result+=allNums.get(i);
else if (allSigns.get(i-1).equals("-"))
result-=allNums.get(i);
else if (allSigns.get(i-1).equals("*"))
result*=allNums.get(i);
else if (allSigns.get(i-1).equals("/"))
result/=allNums.get(i);
else
....
Should do it. 应该这样做。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.