首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 程式設計入門

猜數字遊戲:我的第一個 J2ME 程式(含已知問題)

     編輯:Java 程式設計入門
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import java.util.*;

/**
 * @author aoenzh
 */
public class Test extends MIDlet implements CommandListener {
    private Command cmdOK;
    private Command cmdEXIT;
    private TextField txtInput;
    private Form myForm;
    private int rndNum;
    private Display display;

    public Test() { }

    public void startApp() {
        Random tmpRand = new Random();
        rndNum = tmpRand.nextInt(100); // 產生 0-99 隨機數
        txtInput = new TextField("請輸入 0-50 之間的數字", "", 25, TextField.NUMERIC);
        cmdOK = new Command("確認", Command.SCREEN, 1);
        cmdEXIT = new Command("退出", Command.EXIT, 1);
        myForm = new Form("猜數字");
        myForm.append(txtInput);
        myForm.addCommand(cmdOK);
        myForm.addCommand(cmdEXIT);
        myForm.setCommandListener(this);
        display = Display.getDisplay(this);
        display.setCurrent(myForm);
    }

    public void pauseApp() { }

    public void destroyApp(boolean unconditional) { }

    public void commandAction(Command command, Displayable displayable) {
        if (command == cmdEXIT) {
            destroyApp(true);
            notifyDestroyed();
        }
        if (command == cmdOK) {
            Alert alert = new Alert("猜數字", "", null, AlertType.INFO);
            String input = txtInput.getString();
            int temp;
            if (input.length() > 0) {
                temp = Integer.parseInt(input);
            } else {
                temp = 0;
            }
            alert.setTimeout(3000);
            if (temp > rndNum) {
                alert.setString("大了,笨蛋!");
                Display.getDisplay(this).setCurrent(alert);
            }
            if (temp == rndNum) {
                alert.setString("佩服佩服!");
                Display.getDisplay(this).setCurrent(alert);
                // this.startApp(); // 重新開始遊戲(註解中)
            }
            if (temp < rndNum) {
                alert.setString("小了,笨蛋!");
                Display.getDisplay(this).setCurrent(alert);
            }
            txtInput.setString(""); // 清空輸入框
        }
    }
}

這是我的第一個 J2ME 程式——猜數字遊戲,還有許多問題待解決(如:隨機數範圍與提示不符、遊戲重啟邏輯未完成、輸入驗證不足等),歡迎指教。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved