import java.util.Random;
import java.util.Scanner;
public class caishu {
static int i = 0;
static int p;
public static void main(String[] args) {
// TODO Auto-generated method stub
p = (int) (Math.random() * 100);
//System.out.println(p);
while (i < 5) {
try {
System.out.println("请输入你要猜的数:");
Scanner scanner = new Scanner(System.in);
int s = scanner.nextInt();
if (p != s) {
if (p > s) {
System.out.println("你猜得数小了");
} else {
System.out.println("你猜得数大了");
}
} else {
System.out.println("恭喜你猜对了!");
return;
}
i++;
} catch (Exception ex) {
System.out.println("输入的数据有误!");
}
}
System.out.println("你的猜数次数已经用完了!");
}
}
运行结果
public static void main(String args[]) {
Scanner sc=new Scanner(System.in);
int n=(int) (Math.random()*3);
int k=5,s;
while(k>0){
System.out.println("please input a number");
s=sc.nextInt();
System.out.println(n);
if(s!=n){
System.out.println("wrong answer");
break;
}
System.out.println("You're right");
n=(int) (Math.random()*3);
}
这么简单的程序,初学者应该都会吧。。。。。。。。。随机生成数字,控制台输入scanner..然后比对结果。。。。然后循环5次。