检查小数或点Java

时间:2014-11-10 00:59:54

标签: arrays calculator

我正在研究一个计算器项目。 我正在使用一种方法来分隔char和数值。 但是当我有一个十进制值时,我会遇到问题,因为当十进制值运行时结果显示为0。 这是代码。

List<Double> numbers = new ArrayList<>();
List<Character> operators = new ArrayList<>();
..................

void testing() {

    String userInput = "234+234+234";
    /* ignore the line above its just for understanding */
    /*the above works fine but if we change it to below its dont work.*/
    String userInput = "234+2.3+4.2";
  /*  The both lines above are just for understanding actually i am getting text from edittext*/
    String userInput = currentcalc.getText().toString();
    for (char c : userInput.toCharArray()) {
    	if (!Character.isDigit(c)) {
            s1 = Double.parseDouble(s2);
            numbers.add(s1);
            operators.add(c);
            handler++;
            s2 = "";
            s1 = 0;
    	} else {
            s = Character.toString(c);
            s2 += s;
        }
    }
    result();
}

  

结果= 0.0

s和s2是字符串,s1是double。并且在我的代码中,如果c不是数字,则保存运算符的值,如+, - etc,否则它是保存数字和其他东西的值。我想知道为什么“。”没有通过此代码保存,为什么结果显示为0.0

结果();代码在下面

void result() {

		double total4 = 0;
		s1 = Double.parseDouble(s2);
		numbers.add(s1);
		if (handler < 1) {
			total4 = Double.parseDouble(currentcalc.getText().toString());
		} else {
			int i = 0;
			for (i = 0; i < handler; i++) {

				switch (operators.get(i)) {
				case '/':

					total3 = numbers.get(i) / numbers.get(i + 1);
					total4 = total3;
					numbers.remove(i + 1);
					numbers.set(i, total4);
					operators.remove(i);
					handler--;
					i--;
					break;
				}
			}
			for (i = 0; i < handler; i++) {
				switch (operators.get(i)) {
				case '*':

					total3 = numbers.get(i) * numbers.get(i + 1);
					total4 = total3;
					numbers.remove(i + 1);
					numbers.set(i, total4);
					operators.remove(i);
					handler--;
					i--;
					break;
				}
			}
			for (i = 0; i < handler; i++) {
				switch (operators.get(i)) {
				case '+':

					total3 = numbers.get(i) + numbers.get(i + 1);
					total4 = total3;
					numbers.remove(i + 1);
					numbers.set(i, total4);
					operators.remove(i);
					break;
				case '-':

					total3 = numbers.get(i) - numbers.get(i + 1);
					total4 = total3;
					numbers.remove(i + 1);
					numbers.set(i, total4);
					operators.remove(i);

					break;
				}
				handler--;
				i--;
			}
		}
		et1.setText(Double.toString(total4));
		resettext = 1;
	}

2 个答案:

答案 0 :(得分:1)

按照result()方法,total4在开头设置为0.0,并且当&#34;。&#34;时,没有代码会更改它。遇到运营商。

错误在于你正在治疗&#34;。&#34;作为运营商。在解析循环中使用特殊代码将其视为数字的一部分。您需要更改行if (!Character.isDigit(c)) {,并处理数学逻辑。

答案 1 :(得分:0)

如果您不需要实施任何特定算法,则可以使用:

ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("js");        
Object result = engine.eval("3+4");

否则您可能需要查看以下内容: Shunting Yard Algorithm