使用java File类编写的 猜数小游戏

来源:互联网 发布:python中strip.split 编辑:程序博客网 时间:2024/06/11 09:58

 

  //  猜数 小游戏,娱乐下

 

package cn.itcast.day17.exercise;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Random;

public class Exercise9 {

 public static void main(String[] args) throws IOException {
  int x = new Random().nextInt(100) + 1; // 1-100

  System.out.println("请输入一个1到100以内的整数: ");

  BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

  for(int i = 0; i < 10; i++){
   String line = br.readLine();
   try {
    int num = Integer.parseInt(line);
    if(num > 100 || num < 1)
     System.out.println("请仔细阅读题目, 这是一个1到100以内的数");
    else if (num > x)
     System.out.println("大了");
    else if (num < x)
     System.out.println("小了");
    else {
     System.out.println("对了");
     return;
    }
   } catch(NumberFormatException e) {
    if(line.matches("
\\d+\\.\\d+"))
     System.out.println("请输入一个整数:");
    else if(line.matches(".*\\D.*"))  // 任意字符0到多个 非数字 任意字符0到多个
     System.out.println("您输入的不是数字, 请重新输入:");
    else
     System.out.println("请仔细阅读题目, 这是一个1到100以内的数");
   }
  }
  
  System.out.println("十次都没猜对, 您不适合玩此类游戏!");
 }

}

原创粉丝点击