Android/Java-将整数值从公式转换为双精度

Android/Java-将整数值从公式转换为双精度,java,android,eclipse,calculator,Java,Android,Eclipse,Calculator,我正在创建一个计算器应用程序,它可以在屏幕上显示所有计算步骤,如下所示: 3x5/7*(3/2) 然后,用户只需点击“回车”按钮即可得到结果 问题是我总是得到一个整数值,这很明显,因为我在计算中使用整数值(3、5、7等)。 所以,如果我这样做:1/2,结果将是0,但我希望答案是0.5 更具体地说,我的计算器是这样工作的: 用户点击按钮5,它出现在屏幕上(文本视图)。 然后用户点击按钮/(分割),使用追加方法,屏幕现在显示5/,最后用户点击按钮9,屏幕显示5/9。 当用户点击“回车”时,应用程序从

我正在创建一个计算器应用程序,它可以在屏幕上显示所有计算步骤,如下所示:

3x5/7*(3/2)

然后,用户只需点击“回车”按钮即可得到结果

问题是我总是得到一个整数值,这很明显,因为我在计算中使用整数值(3、5、7等)。 所以,如果我这样做:1/2,结果将是0,但我希望答案是0.5

更具体地说,我的计算器是这样工作的: 用户点击按钮5,它出现在屏幕上(文本视图)。 然后用户点击按钮/(分割),使用追加方法,屏幕现在显示5/,最后用户点击按钮9,屏幕显示5/9。
当用户点击“回车”时,应用程序从屏幕上获取文本并将其存储在字符串变量中,JEXL库将使用该变量(用于计算公式),并给出结果

问题是,我希望数字在屏幕上显示为整数,所以如果我点击9,我不希望它在屏幕上显示为9.0,但还有一个问题,假设我想输入数字“93”,我会先点击9,然后出现9.0,然后点击3,然后出现3.0,给我“数字”9.03.0,它们不存在也不能被使用

那么,哪里有办法将字符串表达式中的整数转换为double? 或者,从整数计算中得到一个双精度值

以下是我的java文件:

public class Main extends Activity implements OnClickListener {

    TextView tv_screen;
    TextView tv_set1;
    TextView tv_set2;

    String screenEvaluation;
    Double screenCalculation;
    JexlEngine jexl = new JexlEngine();

    static final String digits = "0123456789.*/-+^( )√(";
    static final String numbers = "0123456789";
    static final String operators = "*/-+";

    static final String shifteds = "B1";

    Boolean shiftPressed = false;
    Boolean userIsInTheMiddleOfTypingANumber = false;

    Solver solver = new Solver();

    DecimalFormat df = new DecimalFormat("@###########");
    NumberFormat nf = new DecimalFormat("#.####");

    //String buttonPressed;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        /* REMOVE TITLE BAR */

        this.requestWindowFeature(Window.FEATURE_NO_TITLE);

        /* REMOVE NOTIFICATION BAR (AKA FULL SCREEN) */

        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        df.setMinimumFractionDigits(0);
        df.setMinimumIntegerDigits(1);
        df.setMaximumIntegerDigits(8);

        tv_screen = (TextView) findViewById(R.id.tv_screen);
        tv_set1 = (TextView) findViewById(R.id.tv_set1);
        tv_set2 = (TextView) findViewById(R.id.tv_set2);

        findViewById(R.id.button_1).setOnClickListener(this);
        findViewById(R.id.button_2).setOnClickListener(this);
        findViewById(R.id.button_3).setOnClickListener(this);
        findViewById(R.id.button_4).setOnClickListener(this);
        findViewById(R.id.button_5).setOnClickListener(this);
        findViewById(R.id.button_6).setOnClickListener(this);
        findViewById(R.id.button_7).setOnClickListener(this);
        findViewById(R.id.button_8).setOnClickListener(this);
        findViewById(R.id.button_9).setOnClickListener(this);
        findViewById(R.id.button_0).setOnClickListener(this);

        findViewById(R.id.button_multiply).setOnClickListener(this);
        findViewById(R.id.button_divide).setOnClickListener(this);
        findViewById(R.id.button_minus).setOnClickListener(this);
        findViewById(R.id.button_sum).setOnClickListener(this);
        findViewById(R.id.button_root).setOnClickListener(this); 
        findViewById(R.id.button_power).setOnClickListener(this); 
        findViewById(R.id.button_bracket).setOnClickListener(this); 
        findViewById(R.id.button_more_less).setOnClickListener(this); 
        findViewById(R.id.button_dot).setOnClickListener(this); 

        findViewById(R.id.button_shift).setOnClickListener(this);     
        findViewById(R.id.button_enter).setOnClickListener(this); 
        findViewById(R.id.button_clear).setOnClickListener(this); 

    }

    @Override
    public void onClick(View v) {

        String buttonPressed = ((Button) v).getText().toString(); 

        if (digits.contains(buttonPressed)) {

            // digit was pressed
            if (userIsInTheMiddleOfTypingANumber) {

                if (buttonPressed.equals(".") && tv_screen.getText().toString().contains(".")) {
                    // ERROR PREVENTION
                    // Eliminate entering multiple decimals
                } else {

                    if (buttonPressed.equals("( )")) {

                        buttonPressed = "(";

                        if (tv_screen.getText().toString().contains("(")) {

                            buttonPressed = ")";

                        }

                    }

                    if (buttonPressed.equals("√")) {

                        buttonPressed = "√(";

                    }

                    if (operators.contains(buttonPressed)) {

                        tv_screen.append(".0" + buttonPressed);

                    } else {

                        tv_screen.append(buttonPressed);

                    }
                }

            } else {

                if (buttonPressed.equals(".")) {
                    // ERROR PREVENTION
                    // This will avoid error if only the decimal is hit before an operator, by placing a leading zero
                    // before the decimal
                    tv_screen.setText(0 + buttonPressed);
                } else {             

                    if (buttonPressed.equals("( )")) {

                    buttonPressed = "(";

                        if (tv_screen.getText().toString().contains("(")) {

                            buttonPressed = ")";

                        }

                    }

                    if (buttonPressed.equals("√")) {

                        buttonPressed = "√(";

                    }
                    tv_screen.setText(buttonPressed);
                }

                userIsInTheMiddleOfTypingANumber = true;
            }

        } else if (buttonPressed.equals("SHIFT")) {

            if (shiftPressed == true) {

                shiftPressed = false;
                solver.setShift(false);
                tv_set1.setText("");

            } else {

                shiftPressed = true;    
                solver.setShift(true);
                tv_set1.setText("SHIFT");

            }

        } else if (buttonPressed.equals("ENTER")) {

            //solver.performEnterOperation(buttonPressed);
            //tv_screen.setText("DONE!");

            screenEvaluation = tv_screen.getText().toString();
            //screenEvaluation = screenEvaluation.replace("x", "*");
            screenEvaluation = screenEvaluation.replace("√(", "SQRT(");
            Log.w("TAG", "thickness round:" + screenEvaluation);
            Expression e = jexl.createExpression(screenEvaluation);
            JexlContext context = new MapContext();
            String result = e.evaluate(context).toString();

            //Log.w("TAG", "thickness round:" + screenEvaluation);

            tv_screen.setText(result); 

            userIsInTheMiddleOfTypingANumber = false;       

        } else if (shifteds.contains(buttonPressed) && shiftPressed == true) {

            tv_set2.setText(solver.getSetTextView(buttonPressed));

        } else if (buttonPressed.equals("CLEAR")) {

            userIsInTheMiddleOfTypingANumber = false;

            tv_screen.setText("0");

        } else {        

            // operation was pressed
            if (userIsInTheMiddleOfTypingANumber) {

                //Log.w("TAG", "thickness round:" + yyy);

                tv_set2.setText(solver.getSetTextView(buttonPressed));

                solver.setOperand(Double.parseDouble(tv_screen.getText().toString()));
                userIsInTheMiddleOfTypingANumber = false;

            }

            //tv_set2.setText(solver.getSetTextView(buttonPressed));
            solver.performOperation(buttonPressed);
            tv_screen.setText(df.format(solver.getResult()));

        }

    }

}
还有这个,但目前还没有使用:

public class Solver {

    // 3 + 6 = 9
    // 3 & 6 are called the operand.
    // The + is called the operator.
    // 9 is the result of the operation.

    private double mOperand;
    private double mWaitingOperand;
    private String mWaitingOperator;
    private double mCalculatorMemory;

    private Boolean shift;

    private double pressure;
    private double inner_diameter;
    private double allowable_stress;
    private double weld_factor;
    private double y_factor;
    private double corrosion;

    // operator types
    public static final String ADD = "+";
    public static final String SUBTRACT = "-";
    public static final String MULTIPLY = "x";
    public static final String DIVIDE = "/";

    public static final String CLEAR = "C" ;
    public static final String CLEARMEMORY = "MC";
    public static final String ADDTOMEMORY = "M+";
    public static final String SUBTRACTFROMMEMORY = "M-";
    public static final String RECALLMEMORY = "MR";
    public static final String SQUAREROOT = "√";
    public static final String SQUARED = "x²";
    public static final String INVERT = "1/x";
    public static final String TOGGLESIGN = "+/-";
    public static final String SINE = "sin";
    public static final String COSINE = "cos";
    public static final String TANGENT = "tan";

    public static final String ARC = "ARC";
    public static final String B1 = "B1";
    public static final String B2 = "B2";
    public static final String B3 = "B3";
    public static final String B4 = "B4";
    public static final String B5 = "B5";
    public static final String B6 = "B6";

    // public static final String EQUALS = "=";

    // constructor
    public Solver() {
        // initialize variables upon start
        mOperand = 0;
        mWaitingOperand = 0;
        mWaitingOperator = "";
        mCalculatorMemory = 0;

        shift = false;

        pressure = 0;
        inner_diameter = 0;
        allowable_stress = 0;
        weld_factor = 0;
        y_factor = 0;
        corrosion = 0;
    }

    public void setOperand(double operand) {
        mOperand = operand;
    }

    public double getResult() {
        return mOperand;
    }

    // used on screen orientation change
    public void setMemory(double calculatorMemory) {
        mCalculatorMemory = calculatorMemory;
    }

    // used on screen orientation change
    public double getMemory() {
        return mCalculatorMemory;
    }

    public String toString() {
        return Double.toString(mOperand);
    }

    public void setShift(Boolean shiftState) {      
        shift = shiftState;     
    }

    public void setPressure(double setPressure) {
        pressure = setPressure;
    }

    public void setInnerDiameter(double setInnerDiameter) {
        inner_diameter = setInnerDiameter;
    }

    public void setAllowableStress(double setAllowableStress) {
        allowable_stress = setAllowableStress;
    }

    public void setWeldFactor(double setWeldFactor) {
        weld_factor = setWeldFactor;
    }

    public void setYFactor(double setYFactor) {
        y_factor = setYFactor;
    }

    public void setCorrosion(double setCorrosion) {
        corrosion = setCorrosion;
    }

    public String getSetTextView(String setText) {  

        String text;

        if (setText.equals(ARC)) {          
            text = "PIPE";          
            return text;        
        } else if (setText.equals(B1)) {
            text = "PRESSURE";          
            return text;  
        } else if (setText.equals(B2)) {
            text = "INNER DIAMETER";        
            return text;        
        } else if (setText.equals(B3)) {
            text = "ALLOWABLE STRESS";          
            return text;  
        } else if (setText.equals(B4)) {
            text = "WELD FACTOR";           
            return text;  
        } else if (setText.equals(B5)) {
            text = "Y FACTOR";          
            return text;  
        } else if (setText.equals(B6)) {
            text = "CORROSION";
            return text;
        }

        text = "NADA";      
        return text; 

    }

    public double pipeThickness(double inner_pressure, double allowable_stress, double weld_factor, double inner_diameter, double corrosion, double y_factor) {     

        double thickness = ( ( inner_pressure * inner_diameter) + ( 2* allowable_stress * weld_factor * corrosion ) 
                + ( 2 * y_factor * inner_pressure * corrosion ) ) / ( 2* ( ( allowable_stress * weld_factor ) 
                + ( inner_pressure * y_factor ) - inner_pressure ) );

        return thickness;

    }

    protected void performEnterOperation(String operator) {

        if (shift == true) {

            if (operator.equals(B1)) {

                setPressure(mOperand);

            } 

        }

    }

    protected double performOperation(String operator) {

        /*
        * If you are using Java 7, then you can use switch in place of if statements
        *
        *     switch (operator) {
        *     case CLEARMEMORY:
        *         calculatorMemory = 0;
        *         break;
        *     case ADDTOMEMORY:
        *         calculatorMemory = calculatorMemory + operand;
        *         break;
        *     etc...
        *     }
        */

        if (shift == true) {

            if (operator.equals(ARC)) {

                getSetTextView(ARC);
                mOperand = 25.0;

            } 

        } else {

            if (operator.equals(CLEAR)) {
                mOperand = 0;
                mWaitingOperator = "";
                mWaitingOperand = 0;
                // mCalculatorMemory = 0;
            } else if (operator.equals(CLEARMEMORY)) {
                mCalculatorMemory = 0;
            } else if (operator.equals(ADDTOMEMORY)) {
                mCalculatorMemory = mCalculatorMemory + mOperand;
            } else if (operator.equals(SUBTRACTFROMMEMORY)) {
                mCalculatorMemory = mCalculatorMemory - mOperand;
            } else if (operator.equals(RECALLMEMORY)) {
                mOperand = mCalculatorMemory;
            } else if (operator.equals(SQUAREROOT)) {
                mOperand = Math.sqrt(mOperand);
            } else if (operator.equals(SQUARED)) {
                mOperand = mOperand * mOperand;
            } else if (operator.equals(INVERT)) {
                if (mOperand != 0) {
                    mOperand = 1 / mOperand;
                }
            } else if (operator.equals(TOGGLESIGN)) {
                mOperand = -mOperand;
            } else if (operator.equals(SINE)) {
                mOperand = Math.sin(Math.toRadians(mOperand)); // Math.toRadians(mOperand) converts result to degrees
            } else if (operator.equals(COSINE)) {
                mOperand = Math.cos(Math.toRadians(mOperand)); // Math.toRadians(mOperand) converts result to degrees
            } else if (operator.equals(TANGENT)) {
                mOperand = Math.tan(Math.toRadians(mOperand)); // Math.toRadians(mOperand) converts result to degrees                       
            } else {
                performWaitingOperation();
                mWaitingOperator = operator;
                mWaitingOperand = mOperand;
            }

        }

        return mOperand;        

    }

    protected void performWaitingOperation() {

        if (mWaitingOperator.equals(ADD)) {
            mOperand = mWaitingOperand + mOperand;
        } else if (mWaitingOperator.equals(SUBTRACT)) {
            mOperand = mWaitingOperand - mOperand;
        } else if (mWaitingOperator.equals(MULTIPLY)) {
            mOperand = mWaitingOperand * mOperand;
        } else if (mWaitingOperator.equals(DIVIDE)) {
            if (mOperand != 0) {
                mOperand = mWaitingOperand / mOperand;
            }
        }

    }
}
我找到的解决方案是:

if (operators.contains(buttonPressed)) {    

                        tempNumber = Double.parseDouble(tv_screen.getText().toString().replace(tempString, ""));
                        equation = equation + tempNumber.toString() + buttonPressed;                    
                        tempString = tv_screen.getText().toString() + buttonPressed;

                    } 
我创建了3个变量: Double tempNumber,它将从屏幕获取值并将其存储为Double。 字符串表达式,它将表达式存储为具有双值的字符串,因此,“9*3”将是“9.0*3.0”。 字符串tempString,用于“清除”tempNumber变量,将“x”、““/”等替换为“”(无),因此它将仅将数字转换为双精度

最后,我将不从屏幕文本视图中获取公式,而是从公式变量中获取:

tempNumber = Double.parseDouble(tv_screen.getText().toString().replace(tempString, ""));
equation = equation + tempNumber.toString(); 
Expression e = jexl.createExpression(equation);
JexlContext context = new MapContext();
String result = e.evaluate(context).toString();

无论如何,谢谢大家抽出时间

如果您所有的数字都是double类型,尤其是您的答案,这会有所帮助。要强制使用double作为答案,请在执行除法和乘法时使用类型转换或乘以1.0。(字面上是“1.0”,而不仅仅是“1”)

如果要从可以使用的字符串中解析double

Double.parseDouble(sValue);
您还可以在方程行中使用explisit转换,以便执行以下操作:

(double)inum*(double)inum1*(double)inum2/(double)inum4*((double)inum5/(double)inum6)

结果应该是双精度的,而不是整数。

Java默认支持整数运算。 要以float或double(小数点值)形式获得结果,我们应该对float或double数据类型执行操作。 例如:

double x = 3.0/2.0
将给您x作为1.5:) 但是,

将为您提供1,在这种情况下,您不喜欢该选项:(
希望,这有助于你

如果你真的想做一个计算器应用程序,你需要使用BigDeCimple而不是双:/,你需要重构一些代码,但是你要做的正是你想要的……你可能想考虑使用你在求解器类中声明的最后一个字符串给操作员(IE)√") 不要在你发布的第一个类中测试它们的相等性。可读性更强,拼写错误的机会更少。@GhostDerfel,谢谢你的评论,我会阅读BigDecimal,看看它是否符合我的需要。@turbo,谢谢,但我会尝试一次解决一个问题!heheNo问题,如果你需要帮助理解BigDecimal的内容,就让我来吧我知道我无法转换用户点击的每个数字,因为会发生以下错误:用户要键入“93”。他将首先键入“9”,应用程序将其转换为双精度,然后屏幕上将显示“9.0”。好的,现在他键入“3”,应用程序将其转换为double,然后,由于应用程序使用append方法,屏幕上将显示以下内容:“9.03.0”。不幸的是,我无法在整个表达式中使用double.parseDouble(),例如:double.parseDouble(“3*3/5”).=/不,我的意思是,你要做的是像平常一样将它们全部存储为整数,然后当你去做方程时,解析它们。不要在按下它们时解析它们,因为这样会显示出来。你也可以在视图中使用truncate,所以所有内容都被视为整数,但变量都是双精度的。所有建议都是这样.噢,我现在明白了!但我发现了另一个问题,JEXL库从字符串变量获取表达式,然后对其求值以找到答案。应用程序从屏幕(textview)获取字符串变量,因此,如果屏幕显示“9*9”,这就是JEXL库将用来生成答案的内容。因此,变量是否存储为双精度并不重要,只要它在屏幕上显示为整数即可。也许使用RPN系统很容易(请参阅HP计算器)!hahaWell,我创建了一个解决方案,我认为它最接近您的解决方案,所以我接受您的回答。我会编辑我的帖子并将其放在那里。谢谢您,先生。正如我在@w9jds注释中解释的,我不能在用户键入数字时使用double。转换结果(将是整数)是毫无意义的加倍,因为我将失去精度。=/I将给出与此处类似的解释。在计算时仅将值用作加倍。否则,保留为字符串或任何您需要的内容,以使显示看起来正确。:)阅读@w9jds注释中的我的注释=/
double x = 3/2