日期:2014-05-20 浏览次数:20982 次
public static void main(String[] args){ int n = 1, m = 99 ; Scanner sc = new Scanner(System.in); Random r = new Random(); int s = r.nextInt(99) + 1; System.out.println( "猜数游戏\n"); while (true) { System.out.printf( "请输入一个%d-%d之间的数\n", n, m); String str = sc.nextLine(); int i = 0; try { i = Integer.parseInt(str); if (i<n || i>m) { throw new Exception("out of range."); } } catch (Exception e) { System.out.println("输入有误,请重新输入"); continue; } if (i < s) { System.out.printf("输入的数是%d,比中奖号码小,再猜\n", i); m = i; } else if (i > s) { System.out.printf("输入的数是%d,比中奖号码大,再猜\n", i); n = i; } else { System.out.println("输入的数是%d,中奖号码是%d,中奖了\n", i, s); System.out.println("是否继续?请输入[quit]退出"); str = sc.nextLine(); if ("quit".equals(str)) { break; } n = 1; m = 99; s = r.nextInt(99) + 1; } } }
------解决方案--------------------
public class Kaikouzhong { public static void main(String[] args) { int n = 0, m = 99; Random r = new Random(); int z = r.nextInt(100); int s = z + 1; System.out.println("猜数游戏\n"); System.out.println("请输入一个1-99之间的数"); Scanner sc = new Scanner(System.in); int i=0; try{ i = sc.nextInt(); while (i != s) { while (i > 99 || i < 1) { System.out.println("输入有误,请输入一个1-99之间的数"); i = sc.nextInt(); } System.out.println("输入的数为" + i); if (i > s) { System.out.println(n + " 到 " + i); m = i; System.out.println("请输入一个" + n + "到" + m + "之间的数"); i = sc.nextInt(); } else { System.out.println(i + " 到 " + m); n = i; System.out.println("请输入一个" + n + "到" + m + "之间的数"); i = sc.nextInt(); } while (i > m || i < n) { System.out.println("输入有误,请输入一个" + n + "到" + m + "之间的数"); i = sc.nextInt(); } } System.out.println("中奖号码为" + s); System.out.println("中奖了"); }catch(Exception e){ System.out.println("==只能输入数字!游戏结束=="); } } }