要求
一个游戏类Game有两个成员变量v、num,
v有一个初值1,v的取值范围为1到6。
定义一个方法throw,扔色子,随机产生1-6的值
定义一个方法guess,弹出提示框,让用户输入一个整数来猜,保存到num.
对Game类的成员变量v,用num进行猜。如果大了则提示大了,小了则提示小了。
等于则提示猜测成功。
代码
import javax.swing.JOptionPane;
public class dicing
{
int v=1;//1~6
int num;
//扔骰子
public void Throw()
{
v=(int)(Math.random()*6+1);//1~6
}
//开始界面
public void Init()
{
Throw();
int choice=JOptionPane.showConfirmDialog(null,"是否开始猜骰子游戏","是否开始",JOptionPane.YES_NO_OPTION);
if(choice==JOptionPane.YES_OPTION)
{
JOptionPane.showMessageDialog(null,"游戏开始!");
guess();
}
else {
JOptionPane.showMessageDialog(null,"下次再见!");
return;
}
}
//开始游戏
public void guess()
{
String input=JOptionPane.showInputDialog("请输入1--6之间的数字");
num=Integer.parseInt(input);
while(num<0||num>6)
{
JOptionPane.showMessageDialog(null, "请检测后重新输入1--6之间的数字","【出错啦】" ,
JOptionPane.ERROR_MESSAGE);
guess();
}
if(num<v)
{
Object[] options = { "继续" };
JOptionPane.showOptionDialog(null, "小了", "不正确", JOptionPane.DEFAULT_OPTION,
JOptionPane.WARNING_MESSAGE, null, options, options[0]);
guess();
}
else if(num>v)
{
Object[] options = { "继续" };
JOptionPane.showOptionDialog(null, "大了", "不正确", JOptionPane.DEFAULT_OPTION,
JOptionPane.WARNING_MESSAGE, null, options, options[0]);
guess();
}
else if(num==v)
{
JOptionPane.showMessageDialog(null,"答案正确!");
withdraw();
}
}
//一轮游戏结束
public void withdraw()
{
int choice=JOptionPane.showConfirmDialog(null,"是否开始下一轮游戏","是否继续",JOptionPane.YES_NO_OPTION);
if(choice==JOptionPane.YES_OPTION)
{
guess();
}
else {
JOptionPane.showMessageDialog(null,"下次再见!");
System.exit(0);
}
}
//
public static void main(String[] args)
{
dicing a;
a=new dicing();
a.Init();
}
}
运行结果