Written by
Bruth_Lee in Southwest university of Science and Technology
*Java入门之数字猜想
*数字的范围为[1,100]
*数字猜想——适合初学者的一个小编程游戏
package primer_java;
import java.util.Scanner;
public class Guessig_game {
public static void main(String[] args) {
int number=(int)(Math.random()*100+1);//Math.random()是一个范围在[0,1)的随机函数,
//乘以100的范围为[0,100),加一后范围是[1,101),也就是[1,100],由于猜想的数是整数,所以强制转换为int
int a;//用户输入的猜想数
int count=0;
Scanner in = new Scanner(System.in);//构造一个Scanner,前面已经有过介绍
System.out.print("Please enter the number you guess:");
do {
a = in.nextInt();
if(a>number) {
System.out.print("The number you have entered is too large,please retype a smaller number:");
}
else if(a<number) {
System.out.print("The number you have entered is too small,please retype a larger number:");
}
count++;
}while(a!=number);
System.out.println();
System.out.println("The correct answer is "+number+"."+"Congratulations on your guessing.You've got a total of "+count+" times");
}
}