分享几道循环的练习题

今天有感而发,看到下面几道习题,分享一下:
1.随机生成5个[1,36]之间的整数作为彩票中奖号码,对生成的数进行判断,不能有重复号码
如果出现重复,需要重新生成.

public class Caipiao {
	public static void main(String[] args) {
		int a=(int)(Math.random()*36+1);
		int b=(int)(Math.random()*36+1);
		int c=(int)(Math.random()*36+1);
		int d=(int)(Math.random()*36+1);
		int e=(int)(Math.random()*36+1);
		System.out.println(a+" "+b+" "+c+" "+d+" "+e);
	while(true){
		if(b==a){
			 b=(int)(Math.random()*36+1);
		}else{
			break;
		}
	}
	while(true){
	    if(c==a||c==b){
			 c=(int)(Math.random()*36+1);
		}else{
			break;
		}
	}
	while(true){
		if(d==a||d==b||d==c){
			 b=(int)(Math.random()*36+1);
		}else{
			break;
		}
	}
	while(true){
		if(e==a||e==b||e==c||e==d){
			 b=(int)(Math.random()*36+1);
		}else{
			break;
		}
	}
	System.out.println(a+" "+b+" "+c+" "+d+" "+e);	
	}
}

2.判断一个数是否是素数。
import java.util.Scanner;//导包
/*

  • 如何判断一个数为素数呢
  • 不被1和自己整除的数叫做素数.
    */
public class Panduan {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		System.out.println("请输入数字"); // 键盘输入
		int i = sc.nextInt();
		// 判断是否为素数
		boolean flag = true; //循环开始的入口 
		if (i == 1) {        
			flag = false;    //直接输出
		} else {
			for (int j = 2; j < i; j++) {
				if (i % j == 0) {
					flag = false;
					break;
				}
			}
		}
		if (flag) {    //如果flag=true输出
			System.out.println(i + "是素数");
		} else {
			System.out.println(i + "不是素数");
		}
	}
}

3.从键盘输入一个班5个学生的分数,求和并输出。

import java.util.Scanner;
public class sum{
public static void main(Sting[] args){
Scanner sc =new Scanner(System.in);
int sum=sc.nextInt();
for(int i=1;i<=5;i++){
System.out.in("请输入第"+i+"个同学的成绩")
int a=sc.nextInt();
sum=sum+a;
}
System.out.println("总分是" + sum);
	}

}

4.输入一批整数,使用循环求出最大值与最小值,输入0时结束。
import java.util.Scanner;
/*

  • 输入几个数判断谁是最大的最小的
    */
public class Test3 {
	public static void main(String[] args) {
		Scanner D = new Scanner(System.in);
		int max = 0;
		int min = 0;
		int i = 1;
		// 输入第一个数判断它是最大的
		System.out.println("输入第一个数");
		i = D.nextInt();// 再次使用局部变量时,不要要加
		max = i;
		min = i;
		// 依次输入其它数字,判断是否为最大值或最小值
		for (int j = 2; i != 0; j++) {
			System.out.println("请输入第" + j + "二个数");
			i = D.nextInt();
			if (i != 0) {
				if (i > max) {
					max = i;
				}
				if (i < min) {
					min = i;
				}
			}
		}
		// 输出最大值和最小值
		System.out.println("最大值为:" + max);
		System.out.println("最小值为:" + min);
	}
}

猜你喜欢

转载自blog.csdn.net/weixin_45116848/article/details/90690974