當前位置:編程學習大全網 - 編程語言 - 用JAVA編寫壹個小遊戲

用JAVA編寫壹個小遊戲

前天寫的猜數字遊戲,yong?i控制猜測次數,有詳細解析,用黑窗口可以直接運行,

我試驗過了,沒問題

import javax.swing.Icon;

import javax.swing.JOptionPane;

public class CaiShuZi4JOptionPane {

/**

* @param args

*/

public static void main(String[] args) {

Icon icon = null;

boolean bl = false;

int put = 0;

int c = (int) (((Math.random())*100)+1); //獲取壹個1-100的隨機數

System.out.println("妳獲取的隨機數是:"+c); //打印妳的隨機數字

String str1 = (String) JOptionPane.showInputDialog(null,"請輸入妳的猜測數字(1-100):\n","猜數字遊戲",JOptionPane.PLAIN_MESSAGE,icon,null,"在這輸入"); //第壹次輸入妳的猜測數字

if(str1==null){

JOptionPane.showMessageDialog(null, "妳已經取消了本次遊戲"); //如果妳點取消那麽本次遊戲結束

}else{

bl = num(str1); //判斷是輸入的是不是數字或者是整數

if(true==bl){ //如果是數字的話進入與隨機數比較的程序

System.out.println("妳輸入的數字是:"+str1); //打印妳輸入的數字

put = Integer.valueOf(str1);

for(int i = 4;i > 0;i--){ //i是妳可以猜測的次數

if(put==c){

JOptionPane.showMessageDialog(null, "恭喜妳猜對了,正確答案是:"+c+"。"); //如果妳猜對了就直接結束循環

break;

}else if(put>c){ //如果輸大了就讓妳再次從新輸入

str1 = (String) JOptionPane.showInputDialog(null,"妳的輸入過大。妳還有"+i+"次機會,請重新輸入:\n","猜數字遊戲",JOptionPane.PLAIN_MESSAGE,icon,null,"在這輸入");

if(str1==null){

JOptionPane.showMessageDialog(null, "妳已經取消了本次輸入");

break;

}else{

bl =num(str1);

if(true==bl){

put = Integer.valueOf(str1);

}else{

JOptionPane.showMessageDialog(null, "妳的輸入不正確,請重新輸入");

}

}

}else if(put<c){ //如果妳輸小了也讓妳從新輸入

str1 = (String) JOptionPane.showInputDialog(null,"妳的輸入過小。妳還有"+i+"次機會,請重新輸入:\n","猜數字遊戲",JOptionPane.PLAIN_MESSAGE,icon,null,"在這輸入");

if(str1==null){

JOptionPane.showMessageDialog(null, "妳已經取消了本次輸入");

break;

}else{

bl =num(str1);

if(true==bl){

put = Integer.valueOf(str1);

}else{

JOptionPane.showMessageDialog(null, "妳的輸入不正確,請重新輸入");

}

}

}

}

}else if(bl==false){ //這個 是妳第壹次如果填寫的不是數字的話也會結束本次遊戲

JOptionPane.showMessageDialog(null, "請您下次按要求填寫。本次遊戲結束");

}

if(true==bl && c!=put){ //如果妳i次都沒猜對,那麽就直接告訴妳這個數十什麽

JOptionPane.showMessageDialog(null, "很遺憾妳沒能猜對,這個數字是:"+c+".");

}

}

}

public static boolean num(String value){ //壹個靜態方法,判斷妳輸入的是不是數字

try {

Integer.parseInt(value);

return true;

} catch (Exception e) {

return false;

}

}

}

  • 上一篇:大學生鑒定表自我總結
  • 下一篇:中小學校長論壇發言稿
  • copyright 2024編程學習大全網