从字符中随机获取一个字符,提示用户输入数字,或是大写字母,或是小写字母,如果用户猜的数字正确,提示用户,恭喜你猜对了,否则提示输入大了或者输入小了

时间:2023-01-08 08:37:21

package day03;

import java.util.Random;

import javax.swing.JOptionPane;

/*1.当输入的数字与随机产生的数字相同。提示恭喜你中500万日元
 2.当输入的数字小于  提示输入小
 3.当输入的数字大了 提示输入大了
 输入5次没有猜中。对不起游戏结束

 5.如果字母就提示输入字母 如果数字就提示输入数字

 8.如果大写的字母 提示大写字母
 */
public class GuessNumDemo {

 // 入口方法
 public static void main(String[] args) {
  String str = "123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
  // 随机产生字符
  Random random = new Random();
  String inputChar = "";
  int index = random.nextInt(str.length());
  char guessChar = str.charAt(index);
  //JOptionPane.showMessageDialog(null, guessChar);//用于测试,让所猜的字符显示出来,测试程序的正误

  /*
   * if((guessChar>='1')&&(guessChar<='9')){
   * inputChar=JOptionPane.showInputDialog("请输入你猜的数字"); }else
   * if(((guessChar
   * >='a')&&(guessChar<='z'))||((guessChar>='A')&&(guessChar<='Z'))){
   * inputChar=JOptionPane.showInputDialog("请输入你猜的字母"); }
   */

  for (int i = 0; i < 5; i++) {
   if (guessChar >= 49 && guessChar <= 57) {
    inputChar = JOptionPane.showInputDialog("请输入你猜的数字");
    if (inputChar.charAt(0) >= 49 && inputChar.charAt(0) <= 57) {
     if (inputChar.equals(guessChar + "")) {
      JOptionPane.showMessageDialog(null, "恭喜你中了500万!");
      break;
     } else {
      if (inputChar.charAt(0) > guessChar) {
       JOptionPane.showMessageDialog(null, "大了!");
      } else if (inputChar.charAt(0) < guessChar) {
       JOptionPane.showMessageDialog(null, "小了!");
      }
     }
    } else {
     JOptionPane.showMessageDialog(null, "输入错误!");
    }
   } else if ((guessChar >= 97 && guessChar <= 122)) {
    inputChar = JOptionPane.showInputDialog("请输入你猜的小写字母");
    if (inputChar.charAt(0) >= 97 && inputChar.charAt(0) <= 122) {
     if (inputChar.equals(guessChar + "")) {
      JOptionPane.showMessageDialog(null, "恭喜你中了500万!");
      break;
     } else {
      if (inputChar.charAt(0) > guessChar) {
       JOptionPane.showMessageDialog(null, "大了!");
      } else if (inputChar.charAt(0) < guessChar) {
       JOptionPane.showMessageDialog(null, "小了!");
      }
     }
    } else {
     JOptionPane.showMessageDialog(null, "输入错误!");
    }
   } else if ((guessChar >= 65 && guessChar <= 90)) {

    inputChar = JOptionPane.showInputDialog("请输入你猜的大写字母");
    if (inputChar.charAt(0) >= 65 && inputChar.charAt(0) <= 90) {
     if (inputChar.equals(guessChar + "")) {
      JOptionPane.showMessageDialog(null, "恭喜你中了500万!");
      break;
     } else {
      if (inputChar.charAt(0) > guessChar) {
       JOptionPane.showMessageDialog(null, "大了!");
      } else if (inputChar.charAt(0) < guessChar) {
       JOptionPane.showMessageDialog(null, "小了!");
      }
     }
    } else {
     JOptionPane.showMessageDialog(null, "输入错误!");
    }
   }
  }
 }
}