赞
踩
主要是一个循环,通过Random来生成随机数,再在里面加一些判断语句,要注意的是:我们要保证游戏者输入的是正整数,所以需要添加一个判断语句来判断用户输入的是不是正整数。
里面有得分系统每猜一次扣10分。
说明一下:猜不出来退不出游戏,除非超过了6次(因为里面有一个死循环,会一直弹窗)
- package Java;
-
- import javax.swing.*;
- import java.util.Random;
- import java.util.Scanner;
-
-
- public class Cage {
- public static void main(String[] args) {
- Random number = new Random();
-
- int i = number.nextInt(100) + 1;
-
- JOptionPane.showConfirmDialog(null, "系统会随机生成一正整数(1~100),猜测该数字,猜的次数越少,得分越高,6次猜不中,游戏结束。在这之前你将无法退出程序!!!!!", "提示", JOptionPane.OK_OPTION, JOptionPane.WARNING_MESSAGE);
-
- int count = 1;
-
- int score = 100;
-
-
-
- while (true) {
-
-
- String inf = JOptionPane.showInputDialog(null, "请输入你的猜测的数字:", "输入", JOptionPane.QUESTION_MESSAGE);
-
- if(inf==null||inf.length()<=0){
- JOptionPane.showConfirmDialog(null, "请输入正整数", "提示", JOptionPane.OK_OPTION, JOptionPane.WARNING_MESSAGE);
- continue;
- }
-
- isNumeric(inf);
-
- if(isNumeric(inf)==false){
- JOptionPane.showConfirmDialog(null, "请输入正整数", "提示", JOptionPane.OK_OPTION, JOptionPane.WARNING_MESSAGE);
- continue;
- }
- int info=Integer.parseInt(inf);
-
- if (info > 100 || info < 1) {
- JOptionPane.showConfirmDialog(null, "请输入1~100的正整数", "提示", JOptionPane.OK_OPTION, JOptionPane.WARNING_MESSAGE);
- continue;
- }
-
- if (info > i) {
- JOptionPane.showConfirmDialog(null, "猜大了", "提示", JOptionPane.OK_OPTION, JOptionPane.WARNING_MESSAGE); //确认对话框
- } else if (info < i) {
- JOptionPane.showConfirmDialog(null, "猜小了", "提示", JOptionPane.OK_OPTION, JOptionPane.WARNING_MESSAGE); //确认对话框
- } else if (info == i) {
- JOptionPane.showConfirmDialog(null, "猜中了!" + "得分:" + score, "提示", JOptionPane.OK_OPTION, JOptionPane.PLAIN_MESSAGE); //确认对话框
- break;
- }
- if (count == 6) {
- JOptionPane.showConfirmDialog(null, "Game over" + " " + "你好菜啊!", "Game over", JOptionPane.OK_OPTION, JOptionPane.PLAIN_MESSAGE);
- break;
- }
- count++;
- score = score - 10;
-
- }
- }
-
- public static boolean isNumeric(String str){
- for (int i = str.length();--i>=0;){
- if (!Character.isDigit(str.charAt(i))){
- return false;
- }
- }
- return true;
- }
- }

添加主类
接着
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。