猜数字游戏

    1. 程序设计思想:
      程序首先产生一个随机数,接着循环执行:
          显示输入框,用户输入数据,如果用户猜错,提示“猜大了”或“才”小了,直到用户猜对。
      提示“猜对了”。程序结束。
    2. 程序流程图:

    3. 源代码:
       1 import javax.swing.JOptionPane;
       2 public class Guess {
       3     public static void main(String[] args) {
       4         int rand = (int)(Math.random() * 100 + 1);
       5         int n;
       6         do{
       7             String s = JOptionPane.showInputDialog("输入你猜的数字");
       8             if(s == null || s.equals(""))        //如果点击取消或者没有输入数字,直接退出
       9                 return;
      10         n = Integer.parseInt(s);
      11         if(n > rand)
      12             JOptionPane.showMessageDialog(null, "猜大了");
      13         else if(n < rand)
      14             JOptionPane.showMessageDialog(null, "猜小了");
      15         }while(n != rand);
      16         JOptionPane.showMessageDialog(null, "猜对了");
      17     }
      18 }
    4. 运行结果截图:

       

    5. 编译错误分析:

        1) Type mismatch: cannot convert from String to int:

        JOptionPane.showInputDialog(string)返回值类型为string,不可直接赋值给int型变量n

posted @ 2017-10-07 14:26  ╄冷丶夜♂  阅读(164)  评论(0编辑  收藏  举报