Eclipse中的数字平方不起作用

Posted

技术标签:

【中文标题】Eclipse中的数字平方不起作用【英文标题】:Square of a number in Eclipse not working 【发布时间】:2015-06-29 13:27:58 【问题描述】:

这是我正在制作的 android 计算器应用程序的代码:

package com.example.calculator;

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Iterator;
import java.util.Stack;
import java.lang.Math;

import android.app.Activity;
import android.os.Bundle;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.view.View;
import android.view.View.OnClickListener;

public class main extends Activity 
    GridView mKeypadGrid;
    TextView userInputText;
    TextView memoryStatText;

    Stack<String> mInputStack;
    Stack<String> mOperationStack;

    KeypadAdapter mKeypadAdapter;
    TextView mStackText;
    boolean resetInput = false;
    boolean hasFinalResult = false;

    String mDecimalSeperator;
    double memoryValue = Double.NaN;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);

        DecimalFormat currencyFormatter = (DecimalFormat) NumberFormat
                .getInstance();
        char decimalSeperator = currencyFormatter.getDecimalFormatSymbols()
                .getDecimalSeparator();
        mDecimalSeperator = Character.toString(decimalSeperator);

        setContentView(R.layout.main);

        // Create the stack
        mInputStack = new Stack<String>();
        mOperationStack = new Stack<String>();

        // Get reference to the keypad button GridView
        mKeypadGrid = (GridView) findViewById(R.id.grdButtons);

        // Get reference to the user input TextView
        userInputText = (TextView) findViewById(R.id.txtInput);
        userInputText.setText("0");

        memoryStatText = (TextView) findViewById(R.id.txtMemory);
        memoryStatText.setText("");

        mStackText = (TextView) findViewById(R.id.txtStack);

        // Create Keypad Adapter
        mKeypadAdapter = new KeypadAdapter(this);

        // Set adapter of the keypad grid
        mKeypadGrid.setAdapter(mKeypadAdapter);

        // Set button click listener of the keypad adapter
        mKeypadAdapter.setOnButtonClickListener(new OnClickListener() 
            @Override
            public void onClick(View v) 
                Button btn = (Button) v;
                // Get the KeypadButton value which is used to identify the
                // keypad button from the Button's tag
                KeypadButton keypadButton = (KeypadButton) btn.getTag();

                // Process keypad button
                ProcessKeypadInput(keypadButton);
            
        );

        mKeypadGrid.setOnItemClickListener(new OnItemClickListener() 
            public void onItemClick(AdapterView<?> parent, View v,
                    int position, long id) 

            
        );

    

    private void ProcessKeypadInput(KeypadButton keypadButton) 
        //Toast.makeText(this, keypadButton.getText(), Toast.LENGTH_SHORT).show();
        String text = keypadButton.getText().toString();
        String currentInput = userInputText.getText().toString();

        int currentInputLen = currentInput.length();
        String evalResult = null;
        double userInputValue = Double.NaN;

        switch (keypadButton) 
        case BACKSPACE: // Handle backspace
            // If has operand skip backspace
            if (resetInput)
                return;

            int endIndex = currentInputLen - 1;

            // There is one character at input so reset input to 0
            if (endIndex < 1) 
                userInputText.setText("0");
            
            // Trim last character of the input text
            else 
                userInputText.setText(currentInput.subSequence(0, endIndex));
            
            break;
        case SIGN: // Handle -/+ sign
            // input has text and is different than initial value 0
            if (currentInputLen > 0 && currentInput != "0") 
                // Already has (-) sign. Remove that sign
                if (currentInput.charAt(0) == '-') 
                    userInputText.setText(currentInput.subSequence(1,
                            currentInputLen));
                
                // Prepend (-) sign
                else 
                    userInputText.setText("-" + currentInput.toString());
                
            
            break;
        case CE: // Handle clear input
            userInputText.setText("0");
            break;
        case SQUARE:
            double squareInput = Double.valueOf(currentInput);
            userInputText.setText(squareInput+"*"+squareInput);
            break;
        case C: // Handle clear input and stack
            userInputText.setText("0");
            clearStacks();
            break;
        case DECIMAL_SEP: // Handle decimal separator
            if (hasFinalResult || resetInput) 
                userInputText.setText("0" + mDecimalSeperator);
                hasFinalResult = false;
                resetInput = false;
             else if (currentInput.contains("."))
                return;
            else
                userInputText.append(mDecimalSeperator);
            break;
        case DIV:
        case PLUS:
        case MINUS:
        case MULTIPLY:
            if (resetInput) 
                mInputStack.pop();
                mOperationStack.pop();
             else 
                if (currentInput.charAt(0) == '-') 
                    mInputStack.add("(" + currentInput + ")");
                 else 
                    mInputStack.add(currentInput);
                
                mOperationStack.add(currentInput);
            

            mInputStack.add(text);
            mOperationStack.add(text);

            dumpInputStack();
            evalResult = evaluateResult(false);
            if (evalResult != null)
                userInputText.setText(evalResult);

            resetInput = true;
            break;
        case CALCULATE:
            if (mOperationStack.size() == 0)
                break;

            mOperationStack.add(currentInput);
            evalResult = evaluateResult(true);
            if (evalResult != null) 
                clearStacks();
                userInputText.setText(evalResult);
                resetInput = false;
                hasFinalResult = true;
            
            break;
        case M_ADD: // Add user input value to memory buffer
            userInputValue = tryParseUserInput();
            if (Double.isNaN(userInputValue))
                return;
            if (Double.isNaN(memoryValue))
                memoryValue = 0;
            memoryValue += userInputValue;
            displayMemoryStat();

            hasFinalResult = true;

            break;
        case M_REMOVE: // Subtract user input value to memory buffer
            userInputValue = tryParseUserInput();
            if (Double.isNaN(userInputValue))
                return;
            if (Double.isNaN(memoryValue))
                memoryValue = 0;
            memoryValue -= userInputValue;
            displayMemoryStat();
            hasFinalResult = true;
            break;
        case MC: // Reset memory buffer to 0
            memoryValue = Double.NaN;
            displayMemoryStat();
            break;
        case MR: // Read memoryBuffer value
            if (Double.isNaN(memoryValue))
                return;
            userInputText.setText(doubleToString(memoryValue));
            displayMemoryStat();
            break;
        case MS: // Set memoryBuffer value to user input
            userInputValue = tryParseUserInput();
            if (Double.isNaN(userInputValue))
                return;
            memoryValue = userInputValue;
            displayMemoryStat();
            hasFinalResult = true;
            break;
        default:
            if (Character.isDigit(text.charAt(0))) 
                if (currentInput.equals("0") || resetInput || hasFinalResult) 
                    userInputText.setText(text);
                    resetInput = false;
                    hasFinalResult = false;
                 else 
                    userInputText.append(text);
                    resetInput = false;
                

            
            break;

        

    

    private void clearStacks() 
        mInputStack.clear();
        mOperationStack.clear();
        mStackText.setText("");
    

    private void dumpInputStack() 
        Iterator<String> it = mInputStack.iterator();
        StringBuilder sb = new StringBuilder();

        while (it.hasNext()) 
            CharSequence iValue = it.next();
            sb.append(iValue);

        

        mStackText.setText(sb.toString());
    

    private String evaluateResult(boolean requestedByUser) 
        if ((!requestedByUser && mOperationStack.size() != 4)
                || (requestedByUser && mOperationStack.size() != 3))
            return null;

        String left = mOperationStack.get(0);
        String operator = mOperationStack.get(1);
        String right = mOperationStack.get(2);
        String tmp = null;
        if (!requestedByUser)
            tmp = mOperationStack.get(3);

        double leftVal = Double.parseDouble(left.toString());
        double rightVal = Double.parseDouble(right.toString());
        double result = Double.NaN;

        if (operator.equals(KeypadButton.DIV.getText())) 
            result = leftVal / rightVal;
         else if (operator.equals(KeypadButton.MULTIPLY.getText())) 
            result = leftVal * rightVal;

         else if (operator.equals(KeypadButton.PLUS.getText())) 
            result = leftVal + rightVal;
         else if (operator.equals(KeypadButton.MINUS.getText())) 
            result = leftVal - rightVal;
        

        String resultStr = doubleToString(result);
        if (resultStr == null)
            return null;

        mOperationStack.clear();
        if (!requestedByUser) 
            mOperationStack.add(resultStr);
            mOperationStack.add(tmp);
        

        return resultStr;
    

    private String doubleToString(double value) 
        if (Double.isNaN(value))
            return null;

        long longVal = (long) value;
        if (longVal == value)
            return Long.toString(longVal);
        else
            return Double.toString(value);

    

    private double tryParseUserInput() 
        String inputStr = userInputText.getText().toString();
        double result = Double.NaN;
        try 
            result = Double.parseDouble(inputStr);
         catch (NumberFormatException nfe) 
        

        return result;

    

    private void displayMemoryStat() 
        if (Double.isNaN(memoryValue)) 
            memoryStatText.setText("");
         else 
            memoryStatText.setText("M = " + doubleToString(memoryValue));
        
    


要找到输入数字的平方,我使用以下代码:

case SQUARE:
    double squareInput = Double.valueOf(currentInput);
    userInputText.setText(squareInput+"*"+squareInput);
    break;

但是当输入数字 9 和 9 时,它只显示 *9*9.* 它不显示输出为 81

这是为什么,有人可以帮我解决吗?

【问题讨论】:

【参考方案1】:

您通过添加“*”将数字转换为字符串。相反,您需要的是:

userInputText.setText(String.valueOf(squareInput*squareInput));

它的工作方式是:

首先它看到 9 然后你附加一个返回 9 的字符串 "" 现在你将另一个双精度附加到现有字符串中,将 9 附加到现有字符串中,因此你得到 "9*9"

【讨论】:

【参考方案2】:

您的公式不正确。 试试这个。

double squareInput = Double.valueOf(currentInput);
userInputText.setText(String.format("%f", squareInput * squareInput));

【讨论】:

【参考方案3】:

您正在设置字符串值而不是平方计算值。

这样做:

userInputText.setText(String.valueOf(squareInput*squareInput));

【讨论】:

【参考方案4】:

您只需将值连接为字符串。如果您需要计算什么平方并将其添加到文本字段中:

userInputText.setText(squareInput+"*"+squareInput+"="+(squareInput*squareInput) );

【讨论】:

【参考方案5】:

使用下面的代码...可能对你有帮助..

case SQUARE:

double squareInput = Double.valueOf(currentInput);
userInputText.setText(String.valueOf(squareInput*squareInput));
break;

【讨论】:

【参考方案6】:

把你的代码改成这个

case SQUARE:
double squareInput = Double.valueOf(currentInput);
userInputText.setText(""+squareInput*squareInput);
break;

【讨论】:

以上是关于Eclipse中的数字平方不起作用的主要内容,如果未能解决你的问题,请参考以下文章

Win 7 上的 Eclipse Helios 中的 Ctrl 空间不起作用

Eclipse 自动完成功能在某些 Java 文件中不起作用

为啥我的密码不起作用? Eclipse 和 Github [重复]

Eclipse 索引不起作用

风暴拓扑不起作用

当修剪和清除不起作用时删除数字中的空格