编程练习
1、买飞机票
2、找素数
这案例要注意信号位思想,即boolean flag=true;
1. public class PrimeNumber {
2. public static void main(String[] args) {
3. for (int i = 101; i <=200; i++) {
4. boolean flag=true;//信号位,标记,一开始认为这个数是素数
5. for (int j = 2; j < i/2; j++) {
6. if(i%j==0){
7. flag=false;
8. break;
9. }
10. }
11. if(flag)
12. {
13. System.out.print(i+”\t”);
14. }
15. }
16. }
17. }
3、开发验证码【这个项目非常重要】
重点是理解如何生成大小写字母(大写字母65~65+25,小写字母97~97+25),强制类型转换
char ch=(char)(r.nextIn(65)+25);随机type+switch来制造不同类型的字母、运用死循环,使当输入错误时,会重新生成新的验证码,重新验证,应用String类型的比较:a.equals() or a.equalsIgnore()
1. package execise;
2.
3. import java.util.Random;
4. import java.util.Scanner;
5.
6. public class VerificationCode {
7. public static void main(String[] args) {
8. while(true)
9. {
10. String code=createCode(5);
11. System.out.println(“验证码是:”+code);
12. System.out.print(“请输入验证码:”);
13. Scanner sc=new Scanner(System.in);
14. String input=sc.next();
15. if(input.equalsIgnoreCase(code))
16. {
17. System.out.println(“输入正确。”);
18. break;
19. }
20. else
21. {
22. System.out.println(“输入错误,请重新输入。”);
23. }
24. }
25. }
26. //1、首先写一个生成验证码的方法
27. public static String createCode(int n)
28. {
29. //int n代表要生成几位的验证码
30. String code=””;
31. Random r=new Random();
32. for (int i = 0; i < n; i++) {
33. int type=r.nextInt(3);
34. /随机数若生成0,则代表这位用大写字母;
35. 随机数若生成1,则代表这位用小写字母;
36. 随机数若生成2,则代表这位用数字;/
37. switch(type)
38. {
39. case 0://大写字母是从65,到65+25。而且要强制转换类型char
40. char capital=(char)(r.nextInt(26)+65);
41. code+=capital;
42. break;
43. case 1://小写字母是从97到97+25.
44. char lowercase=(char)(r.nextInt(26)+97);
45. code+=lowercase;
46. break;
47. case 2:
48. code+=r.nextInt(10);
49. break;
50. }
51. }
52. return code;
53. }
54.
55. }
1、数组元素复制
2、评委打分(冒泡排序)
3、数字加密(难点:将输入的数据分解存储在数组内)
4、模拟双色球
