calc.java

来自「3D手机游戏开发实例源代码」· Java 代码 · 共 59 行

JAVA
59
字号
import javax.microedition.midlet.MIDlet;
import javax.microedition.lcdui.*;
import com.mascotcapsule.micro3d.v3.Util3D;
public class Calc extends MIDlet implements CommandListener {
    private Command exitCommand  = new Command("Exit",  Command.EXIT, 1);
    private Command clearCommand = new Command("Clear", Command.ITEM, 2);
    private Command calcCommand  = new Command("Calc",  Command.ITEM, 2);
    private Form mainForm;
    private TextField inputField; // 值输入的TextField
    private StringItem answerStr; // 显示计算结果
    protected void startApp() {
        mainForm = new Form("Calculator");
        inputField = new TextField("Input", "", 15, TextField.NUMERIC);
        answerStr = new StringItem("Square root: ", null);
        mainForm.append(inputField);
        mainForm.append(answerStr);
        mainForm.addCommand(exitCommand);
        mainForm.addCommand(clearCommand);
        mainForm.addCommand(calcCommand);
        mainForm.setCommandListener(this);
        System.out.println( Util3D.sqrt(7));
        Display.getDisplay(this).setCurrent(mainForm);
    }
     public void commandAction(Command c, Displayable s) {
        if (c == exitCommand) {
            destroyApp(false);
            notifyDestroyed();
        } else if(c == calcCommand) {
            calcSqrt();
        } else if(c == clearCommand) {    // 清除输入
            answerStr.setText("");
            inputField.setString("");
        }
    }
/*    
    // 输出输入值的平方根
    private void calcSqrt() {
        int input = Integer.parseInt(inputField.getString());
        int answer = Util3D.sqrt(input);
        answerStr.setText("" + answer);    
    }
*/
	
    // 保留输入值的平方根小数点以下三位输出
    private void calcSqrt() {
        int input = Integer.parseInt(inputField.getString()) * 1000 * 1000;
        int answer = Util3D.sqrt(input);
        int integerPart = answer / 1000;
        int decimalFraction1 = (answer - integerPart * 1000) / 100;
        int decimalFraction2 = (answer - integerPart * 1000 - decimalFraction1 * 100) / 10;
        int decimalFraction3 = answer - integerPart * 1000 - decimalFraction1 * 100 - decimalFraction2 * 10;
        String str = "" + integerPart + "." + decimalFraction1 + "" + 
                          decimalFraction2 + "" + decimalFraction3 + "";
        answerStr.setText(str);       
    }
    protected void destroyApp(boolean unconditional) {}
    protected void pauseApp() {}
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?