最近学了一下java,2天半时间(2015年4月21日-2015年4月23日)完成了入门。
通过写一个生成随机密码的小Sample,来进行学习。4月22日了写console版。4月23日早上了写GUI版。至此算是java入门了。4月24日写了Android Application版。
贴一下console版的源码,希望大家可以给予指正。
console版运行效果:
gui版运行效果:
console版源码
RandomPasswordSample2.java
1 // by JIURL
2 // 微博 http://weibo.com/ddqqppb
3 //
4
5 import java.util.Scanner;
6
7 public class RandomPasswordSample2 {
8
9 public static void main(String[] args) {
10 // TODO Auto-generated method stub
11 System.out.printf("******************************\n");
12 System.out.printf("Random Password Generator\n");
13 System.out.printf("by JIURL\n");
14 System.out.printf("******************************\n");
15
16 int nPasswordLength;
17 System.out.printf("input password length: ");
18 Scanner sc = new Scanner(System.in);
19 nPasswordLength = sc.nextInt();
20 sc.close();
21
22 // generate nPass passwords one time to choose
23 final int nPass = 10;
24 RandomPassword[] rndpass = new RandomPassword[nPass];
25
26 int i;
27 for(i=0; i<nPass; i++)
28 {
29 rndpass[i] = new RandomPassword(nPasswordLength);
30 }
31
32 // display the results
33 for(i=0; i<nPass; i++)
34 {
35 System.out.printf("%s\n", rndpass[i].GetRandomPassword());
36 }
37 }
38 }
RandomPassword.java
1 // by JIURL
2 // 微博 http://weibo.com/ddqqppb
3 //
4
5 import java.util.Random;
6
7 public class RandomPassword{
8 private String strRandomPassword;
9 private int nRandomPasswordLength;
10
11 private final static char caAlphabet[] =
12 {
13 ‘a‘, ‘b‘, ‘c‘, ‘d‘, ‘e‘, ‘f‘, ‘g‘, ‘h‘, ‘i‘, ‘j‘, ‘k‘, ‘l‘, ‘m‘,
14 ‘n‘, ‘o‘, ‘p‘, ‘q‘, ‘r‘, ‘s‘, ‘t‘, ‘u‘, ‘v‘, ‘w‘, ‘x‘, ‘y‘, ‘z‘,
15 ‘0‘, ‘1‘, ‘2‘, ‘3‘, ‘4‘, ‘5‘, ‘6‘, ‘7‘, ‘8‘, ‘9‘
16 };
17
18 public RandomPassword( int nRandomPasswordLength ){
19 this.nRandomPasswordLength = nRandomPasswordLength;
20 this.strRandomPassword = CreateRandomPassword( nRandomPasswordLength );
21 }
22
23 private String CreateRandomPassword( int nRandomPasswordLength ){
24 int i;
25
26 Random rnd = new Random();
27 rnd.setSeed(System.nanoTime());
28
29 StringBuilder strBuilder = new StringBuilder("");
30
31 int x;
32 x = Math.abs(rnd.nextInt())%26;
33
34 strBuilder.append(RandomPassword.caAlphabet[x]);
35 for(i=1;i<nRandomPasswordLength;i++)
36 {
37 x = Math.abs(rnd.nextInt())%36;
38 strBuilder.append(RandomPassword.caAlphabet[x]);
39 }
40
41 strRandomPassword = strBuilder.toString();
42
43 return this.strRandomPassword;
44 }
45
46 public String GetRandomPassword(){
47 return strRandomPassword;
48 }
49 }