获取随机数
小练习
1.猜数字小游戏
程序自动生成一个1-100之间的随机数字,使用程序实现猜出这个数字是多少?
public static void main(String[] args) {
Random r=new Random();
int number=r.nextInt(10)+1;//1~10
System.out.println("请猜数字");
Scanner sc=new Scanner(System.in);
int ans=sc.nextInt();
while(true) {
if (ans < number) {
System.out.println("猜小了,请重新猜");
ans = sc.nextInt();
continue;
} else if (ans > number) {
System.out.println("猜大了,请重新猜");
ans = sc.nextInt();
continue;
} else {
System.out.println("猜中了");
break;
}
}
}
2.求质数
从键盘中输入一个整数,判断是不是质数
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int number=sc.nextInt();
int i;
boolean flag=true;
for (i=2;i<=Math.sqrt(number);i++){
if(number%i==0)
{
flag=false;
break;
}
else continue;
}
if(flag)
System.out.println(number+"是质数");
else System.out.println(number+"不是质数");
}
3.求平凡根
用循环求平方根
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int number=sc.nextInt();
int i;
for (i=1;i<number;i++){
if(i*i<=number)
continue;
else break;
}
System.out.println(i-1);
}
4.逢7过
包含7或者7的倍数,1-100
(7的倍数/个位是7/十位是7)
public static void main(String[] args) {
for (int i=1;i<=100;i++){
if((i%7==0)||(i%10==7)||(i/10==7)){
System.out.println("过");
continue;
}
else System.out.println(i);
}
}