一个java的猜数字游戏 适合初学者
源代码在线查看: guessnumber.java
//file GuessNumber.java
//第三章,程序流程.
//通过日期:2003,11,3
//功能:猜四位数,7次机会。
//规模:89
import javax.swing.JOptionPane;//JOptionPane
public class GuessNumber
{
public static void main(String[] args)
{
int a=0;//right number and right position
int b=0;//wrong number and right position
int count;//number of guess
int[] original = new int[4];//right number
int[] guess = new int[4];//number you have guessed
String input;
try{
do{
//product a new number
for(int i=0;i {
original[i] = (int)(Math.random()*10);
for(int j = 0;j {
if((i!=j)&&(original[i]==original[j]))
{
i=i-1;
break;
}
}
}
for(count=0;count {
input = JOptionPane.showInputDialog
("Please input your number(integer)");
int number = Integer.parseInt(input);
guess[0] = number/1000;
guess[1] = number/100 - 10 * guess[0];
guess[2] = number/10 - 100 * guess[0] - 10*guess[1];
guess[3] = number%10;
for(int i = 0;i {
for(int j = 0;j {
if(guess[i]==original[j])
{
if(i==j)a++;
else b++;
}
}
}
if(a==4)
{
JOptionPane.showMessageDialog(null,"You are so clever!",
"You win.",JOptionPane.INFORMATION_MESSAGE);
}
else
{
for(int i = 0;i {
System.out.print(guess[i]);
}
System.out.println(" "+a+"A"+b+"B");
}
a=0;
b=0;
}
JOptionPane.showMessageDialog(null,"You lose!",
"Right number is" + original[0] + original[1]
+ original[2] + original[3],
JOptionPane.INFORMATION_MESSAGE);
input=JOptionPane.showInputDialog
("Do you want to try again?(Y/N)");
input=input.toUpperCase();
}while(input.equals("Y"));
}
catch(Exception e)
{
System.out.println("Something is wrong!");
System.exit(0);
}
}
}