Java實現1到100之間的猜數字游戲(及異常處理)


public class Homework21 {
 public static void main(String[] args) {
  Random rand = new Random();
  Scanner sc = new Scanner(System.in);
  int num = rand.nextInt(100) + 1;
  int t = 0;
  while (true) {
   System.out.println("請輸入1-100之間的整數:");
   try {
    t = sc.nextInt();
   } catch (InputMismatchException e) {
    System.out.println("輸入有誤!請重新輸入");
    sc.next();
    continue;
   }
   if (t < num) {
    System.out.println("太小了!");
   } else if (t > num) {
    System.out.println("太大了!");
   } else {
    System.out.println("恭喜你,答對了!");
    break;
   }
  }
 }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM