java程序设计经典_Java程序设计经典300例

一、基础篇(basic)

1.不借助第三者实现两个变量值的交换:

1 packagebasic;2

3 importjava.util.Scanner;4

5 public classExchangeValue {6 public static voidmain(String[] args) {7 Scanner scan = newScanner(System.in);8 System.out.println("请输入变量A的值:");9 long a =scan.nextLong();10 System.out.println("请输入变量B的值:");11 long b =scan.nextLong();12 System.out.println("a=" + a + "\tb=" +b);13 System.out.println("变量交换...\t");14 a = a ^b;15 b = a ^b;16 a = a ^b;17 System.out.println("a=" + a + "\tb=" +b);18 }19 }

2.利用异或进行加解密:

1 packagebasic;2

3 importjava.util.Scanner;4

5 public classEncryption {6 public static voidmain(String[] args) {7 Scanner scan=newScanner(System.in);8 System.out.println("请输入一个英文字符串或解密字符串");9 String password=scan.nextLine();10 char[] array=password.toCharArray();11 for(int i=0;i

3.利用BigDecimal求和:

1 packagebasic;2

3 importjava.math.BigDecimal;4

5 public classFactorial {6 public static voidmain(String[] args) {7 BigDecimal sum=new BigDecimal(0.0);8 BigDecimal factorial=new BigDecimal(1.0);9 int i=1;10 while(i<=10){11 sum=sum.add(factorial);12 ++i;13 factorial=factorial.multiply(new BigDecimal(1.0/i));14 }15 System.out.println("1+1/2!+1/3!+1/4!....+1/10!="+sum);16 }17 }

4.for循环打印空心菱形:

1 packagebasic;2

3 public classDiamond {4 public static voidmain(String[] args) {5 printDiamond(6);6 }7

8 public static void printDiamond(intsize) {9 if (size % 2 == 0) {10 size++;11 }12 for (int i = 0; i < size / 2 + 1; ++i) {13 for (int j = size / 2 + 1; j > i + 1; j--) {14 System.out.print(" ");15 }16 for (int j = 0; j < 2 * i + 1; j++) {17 if (j == 0 || j == 2 *i) {18 System.out.print("*");19 } else{20 System.out.print(" ");21 }22 }23 System.out.println("");24 }25 for (int i = size / 2 + 1; i < size; i++) {26 for (int j = 0; j < i - size / 2; j++) {27 System.out.print(" ");28 }29 for (int j = 0; j < 2 * size - 1 - 2 * i; j++) {30 if (j == 0 || j == 2 * (size - i - 1)) {31 System.out.print("*");32 } else{33 System.out.print(" ");34 }35 }36 System.out.println("");37 }38 }39 }

5.猴子分桃问题:一堆桃子,5个猴子先后到,每次都均分5份,扔掉多余的一个,拿走自己的那份。问最少有几个桃子,最后一个猴子得到几个桃子。

1 packagebasic;2

3 public classMonkeyPeach {4 public static voidmain(String[] args) {5 int n = 1;6 int m = 0;7 int flag = 1;8 int monkeyNum = 5;9 while (true) {10 flag = 1;11 m = monkeyNum * n + 1;12 for (int i = monkeyNum; i >= 1; i--) {13 if ((m % (monkeyNum - 1) == 0)) {14 m = m / (monkeyNum - 1) * monkeyNum + 1;15 flag++;16 } else{17 break;18 }19 }20 if (flag ==monkeyNum)21 break;22 n++;23 }24 System.out.println("桃子总数为:" +m);25 System.out.println("第五个猴子得到的桃子数为:" +n);26 }27 }

6.约瑟夫问题:

1 packagebasic;2

3 importjavax.swing.JOptionPane;4

5 public classJosephus {6 public static voidmain(String[] args) {7 String s;8 intn, k, m, n1;9 s = JOptionPane.showInputDialog("请输入人数:");10 n =Integer.parseInt(s);11 n1 = n + 1;12 s = JOptionPane.showInputDialog("请输入起始报数的人的编号:");13 k =Integer.parseInt(s);14 s = JOptionPane.showInputDialog("请输入死亡数字:");15 m =Integer.parseInt(s);16 int a[] = new int[n + 1];17 a[0] = 0;18 System.out.println("出局人的编号:");19 for (int i = 1; i < a.length; i++) {20 a[i] = 1;21 }22 for (int i = 1; i <= m; i++) {23 if (n == 1)24 break;25 else if (i ==m) {26 n--;27 i = 0;28 a[k] = 0;29 System.out.print(k + " ");30 }31 do{32 k++;33 k = k %n1;34 } while (a[k] != 1);35 }36 System.out.println("");37 System.out.println("幸存者编号:" +k);38 }39 }

7.数独问题:

1 packagebasic;2

3 importjava.util.Scanner;4

5 public classSudoku {6 public static voidmain(String[] args) {7 Scanner s = newScanner(System.in);8 System.out.println("请输入要计算的数独维数(大于1的奇数):");9 int x =s.nextInt();10 int h = 0;11 int l = x / 2;12 int[][] a = new int[x][x];13 for (int i = 1; i <= x * x; i++) {14 a[h][l] =i;15 h--;16 l++;17 if (h < 0 && l >=x) {18 h += 2;19 l--;20 } else if (h < 0) {21 h = x - 1;22 } else if (l >=x) {23 l = 0;24 } else if (a[h][l] > 0) {25 h += 2;26 l--;27 }28 }29 for (int i = 0; i < x; i++) {30 for (int j = 0; j < x; j++)31 System.out.print(a[i][j] + " ");32 System.out.println();33 }34 }35 }

8.数字格式转为货币字符串:

1 packagebasic;2

3 importjava.text.NumberFormat;4 importjava.util.Locale;5 importjava.util.Scanner;6

7 public classCurrencyFormat {8 public static voidmain(String[] args) {9 Scanner scan = newScanner(System.in);10 System.out.println("请输入一个货币数字:");11 double number =scan.nextDouble();12 NumberFormat format =NumberFormat.getCurrencyInstance(Locale.CHINA);13 System.out.println("Locale.CHINA:" +format.format(number));14 format =NumberFormat.getCurrencyInstance(Locale.US);15 System.out.println("Locale.US:" +format.format(number));16 format =NumberFormat.getCurrencyInstance(Locale.UK);17 System.out.println("Locale.UK:" +format.format(number));18 }19 }

9.检验IP地址:

1 packagebasic;2

3 importjava.util.Scanner;4

5 public classIPAddress {6 public static voidmain(String[] args) {7 Scanner sc = newScanner(System.in);8 System.out.println("请输入需要校验的IP地址:");9 String text =sc.nextLine();10 String info =matches(text);11 System.out.println(info);12 }13

14 public staticString matches(String text) {15 if (text != null && !text.isEmpty()) {16 String regex = "^(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[1-9])\\."

17 + "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\."

18 + "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\."

19 + "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)$";20 if(text.matches(regex)) {21 return text + "是一个合法的IP地址!";22 } else{23 return text + "不是一个合法的IP地址!";24 }25 }26 return "请输入要验证的IP地址!";27 }28 }

10.检验电话号码:

1 packagebasic;2

3 importjava.util.Scanner;4

5 public classPhoneNumber {6 public static voidmain(String[] args) {7 Scanner sc = newScanner(System.in);8 System.out.println("请输入电话号码:");9 String phoneNumber =sc.nextLine();10 System.out.println(check(phoneNumber));11 }12

13 public staticString check(String phoneNumber) {14 if (phoneNumber == null ||phoneNumber.isEmpty())15 return "请输入电话号码";16 String regex = "^\\d{3}-?\\d{8}|\\d{4}-?\\d{8}$";17 if(phoneNumber.matches(regex))18 return phoneNumber + "是一个合法的电话号码!";19 else

20 return phoneNumber + "不是一个合法的电话号码!";21 }22 }

11.字符串编码转换:

1 packagebasic;2

3 importjava.io.UnsupportedEncodingException;4

5 public classChangeCharset {6 public static final String ISO_8859_1 = "ISO-8859-1";7

8 public static final String UTF_8 = "UTF-8";9

10 public static final String GBK = "GBK";11

12 public static final String GB2312 = "GB2312";13

14 public String toISO_8859_1(String str) throwsUnsupportedEncodingException {15 return this.changeCharset(str, ISO_8859_1);16 }17

18 public String toUTF_8(String str) throwsUnsupportedEncodingException {19 return this.changeCharset(str, UTF_8);20 }21

22 public String toGBK(String str) throwsUnsupportedEncodingException {23 return this.changeCharset(str, GBK);24 }25

26 public String toGB2312(String str) throwsUnsupportedEncodingException {27 return this.changeCharset(str, GB2312);28 }29

30 publicString changeCharset(String str, String newCharset)31 throwsUnsupportedEncodingException {32 if (str != null) {33 byte[] bs =str.getBytes();34 return newString(bs, newCharset);35 }36 return null;37 }38

39 publicString changeCharset(String str, String oldCharset, String newCharset)40 throwsUnsupportedEncodingException {41 if (str != null) {42 byte[] bs =str.getBytes(oldCharset);43 return newString(bs, newCharset);44 }45 return null;46 }47

48 public static void main(String[] args) throwsUnsupportedEncodingException {49 ChangeCharset test = newChangeCharset();50 String str = "This is a 中文的 string";51 System.out.println("str:" +str);52 String iso8859_1 =test.toISO_8859_1(str);53 System.out.println("转换为ISO-8859-1:" +iso8859_1);54 String utf_8 =test.toUTF_8(str);55 System.out.println("转换为UTF-8:" +utf_8);56 String gbk =test.toGBK(str);57 System.out.println("转换为GBK码:" +gbk);58 String gb2312 =test.toGB2312(str);59 System.out.println("转换为GB2312码:" +gb2312);60 }61 }

12.StringBuilder,StringBuffer和String的区别:

1 packagebasic;2

3 public classBufferString {4 public static voidmain(String[] args) {5 String string = "";6 long startTime =System.nanoTime();7 for (int i = 20000; i < 50000; ++i)8 string += (char) i;9 long endTime =System.nanoTime();10 System.out11 .println("String耗时:" + (endTime - startTime) / 1000000 + "ms");12 StringBuffer stringBuffer = newStringBuffer();13 startTime =System.nanoTime();14 for (int i = 20000; i < 50000; ++i)15 stringBuffer.append((char) i);16 endTime =System.nanoTime();17 System.out.println("StringBuffer耗时:" + (endTime - startTime) / 1000000

18 + "ms");19 StringBuilder stringBuilder = newStringBuilder();20 startTime =System.nanoTime();21 for (int i = 20000; i < 50000; ++i)22 stringBuilder.append((char) i);23 endTime =System.nanoTime();24 System.out.println("StringBuilder耗时:" + (endTime - startTime) / 1000000

25 + "ms");26 }27 }

13.利用TreeSet模拟数组:

1 packagebasic;2

3 importjava.util.Random;4 importjava.util.TreeSet;5

6 public classNoRepeatRandom {7 public static voidmain(String[] args) {8 TreeSet set = new TreeSet();9 Random ran = newRandom();10 int count = 0;11 while (count < 10) {12 boolean succeed = set.add(ran.nextInt(100));13 if(succeed)14 count++;15 }16 int size =set.size();17 Integer[] array = newInteger[size];18 set.toArray(array);19 System.out.println("生成的随机不重复的数据如下:");20 for (intvalue : array) {21 System.out.print(value + " ");22 }23 }24 }

14.逆序遍历ArrayList:

1 packagebasic;2

3 importjava.util.ArrayList;4 importjava.util.List;5 importjava.util.ListIterator;6

7 public classReverseOrder {8 public static voidmain(String[] args) {9 List list = new ArrayList();10 for (int i = 0; i < 10; ++i)11 list.add(i);12 System.out.println("顺序输出:" +list);13 System.out.print("逆序输出:");14 ListIterator li =list.listIterator();15 for (li =list.listIterator(); li.hasNext();) {16 li.next();17 }18 for(; li.hasPrevious();) {19 System.out.print(li.previous() + " ");20 }21 }22 }

15.用LinkedList实现猴子大王问题:

1 packagebasic;2

3 importjava.util.Iterator;4 importjava.util.LinkedList;5

6 public classMonkey {7 public static voidmain(String[] args) {8 LinkedList monkeys = new LinkedList();9 intnumber, cnt;10 for (number = 1; number <= 100; ++number)11 monkeys.addLast(number);12 cnt = 100;13 number = 0;14 Iterator it =monkeys.iterator();15 while (cnt > 1) {16 if(it.hasNext()) {17 it.next();18 ++number;19 } else{20 it =monkeys.iterator();21 }22 if (number == 14) {23 number = 0;24 it.remove();25 --cnt;26 }27 }28 System.out.println("猴子大王编号为:" +monkeys.element());29 }30 }

16.线程的启动和结束:

1 packagebasic;2

3 importjava.util.Date;4

5 class ThreadX implementsRunnable {6 privateDate runDate;7

8 @SuppressWarnings("deprecation")9 public voidrun() {10 System.out.println("线程X已经启动...");11 this.runDate = newDate();12 System.out.println("启动时间:" +runDate.toLocaleString());13 }14 }15

16 class ThreadY extendsThread {17 private boolean isRunState = false;18

19 public voidstart() {20 this.isRunState = true;21 super.start();22 }23

24 public voidrun() {25 int i = 0;26 try{27 while(isRunState) {28 this.setName("Thread-" + i++);29 System.out.println("线程Y" + this.getName() + "正在运行");30 Thread.sleep(200);31 }32 } catch(Exception e) {33 }34 System.out.println(this.getName() + "结束运行...");35 }36

37 public void setRunning(booleanisRunState) {38 this.isRunState =isRunState;39 }40

41 public voidstartThreadY() {42 System.out.println("启动线程Y...");43 this.start();44 }45

46 public voidstopThreadY() {47 System.out.println("结束线程Y...");48 this.setRunning(false);49 }50 }51

52 public classStartThread {53 public voidstartX() {54 Runnable runnX = newThreadX();55 Thread threadX = newThread(runnX);56 threadX.start();57 }58

59 public voidstartY() {60 ThreadY ty = newThreadY();61 ty.startThreadY();62 try{63 Thread.sleep(1000);64 } catch(Exception e) {65 e.printStackTrace();66 }67 ty.stopThreadY();68 }69

70 public static voidmain(String[] args) {71 StartThread test = newStartThread();72 test.startX();73 test.startY();74 }75 }

17.设置线程优先级:

1 packagebasic;2

3 class Clicker extendsThread {4 private int click = 0;5 private volatile boolean running = true;6

7 public intgetClick() {8 returnclick;9 }10

11 public voidrun() {12 while(running)13 click += 1;14 }15

16 public voidnormalStop() {17 running = true;18 }19 }20

21 public classPri {22 public static voidmain(String[] args) {23 Clicker trHigh, trLow;24 trHigh = newClicker();25 trLow = newClicker();26 trHigh.setPriority(Thread.NORM_PRIORITY + 2);27 trLow.setPriority(Thread.NORM_PRIORITY - 2);28 trLow.start();29 trHigh.start();30 try{31 Thread.sleep(1);32 } catch(InterruptedException e) {33 }34 trHigh.normalStop();35 trLow.normalStop();36 try{37 trHigh.join();38 trLow.join();39 } catch(InterruptedException e) {40 }41 System.out.println("trHigh的循环次数为:" +trHigh.getClick());42 System.out.println("trLow的循环次数为:" +trLow.getClick());43 }44 }

你可能感兴趣的:(java程序设计经典)