一些Java編程題


本文爲學習實踐的記錄,來源於:http://thecodesample.com


package interview;

/*
 * 本文給出一個實例,使用遞歸算法反轉字符串
 */
public class StringReversalWithRecursion {

	public static void main(String[] args) {
		StringReversalWithRecursion test = new StringReversalWithRecursion();
		System.out.println(test.reverseString("abc"));
	}

	public  String reverseString(String str) {
		if (str.isEmpty()) {
			return str;
		}
		return reverseString(str.substring(1)) + str.charAt(0);
	}
}

package interview;

import java.util.Arrays;
/**
 * 寫一個程序,去除有序數組中的重複數字
 * @author xl
 *
 */
public class RemoveDuplicateElementsExample {

	public static void main(String[] args) {

		int[] arr = {1,2,2,3,1,2,3,6,7,6};
		int [] out = removeDuplicateDataInArray(arr);
		System.out.println(Arrays.toString(out));
	}
	
	//移除數組中重複元素
	public  static int[] removeDuplicateDataInArray(int[] arr){
		if (arr == null || arr.length == 0) {
			throw new IllegalArgumentException("原數組不能爲空");
		}
		int len = arr.length;
		if (len == 1) {
			return arr;
		}
		//排序
		Arrays.sort(arr);
		int start = 0;
		int end = 1;
		while(end < len) {
			if (arr[start] == arr[end]) {
				end ++;
			} else {
				arr[++start] = arr[end++];
			}
		}
		int newLen = start + 1;
		int[] newArr = new int[newLen];
		System.arraycopy(arr, 0, newArr, 0, newLen);
		return newArr;
	}

}

package interview;

import java.util.Arrays;

/**
 * 合併兩個有序數組
 * 
 * @author xl
 *
 */
public class MergeTwoSortIntegerArrays {

	// 合併有序數組
	public static int[] merge(int[] a, int[] b) {
		int lena = a.length;
		int lenb = b.length;
		if (a == null || lena == 0) {
			throw new IllegalArgumentException("a數組爲空");
		}
		if (b == null || lenb == 0) {
			throw new IllegalArgumentException("b數組爲空");
		}

		int[] newArr = new int[lena + lenb];
		System.arraycopy(a, 0, newArr, 0, lena);
		System.arraycopy(b, 0, newArr, lena, lenb);
		Arrays.sort(newArr); // 方法1
		return newArr;
	}

	public static int[] merge1(int[] a, int[] b) {
		if (a == null)
			return b;

		if (b == null)
			return a;

		int len1 = a.length;
		int len2 = b.length;

		int result[] = new int[len1 + len2];
		int i = 0;
		int j = 0;
		int k = 0;
		while (i < len1 && j < len2) {
			if (a[i] < b[j]) {
				result[k++] = a[i];
				i++;
			} else {
				result[k++] = b[j];
				j++;
			}
		}
		System.arraycopy(a, i, result, k, (len1 - i));
		System.arraycopy(b, j, result, k, (len2 - j));
		return result;
	}

	public static void main(String[] args) {
		long t1 = System.nanoTime();
		int[] a = { -1, 5, 9, 15, 85, 98, 100 };
		int[] b = { -2, 6, 8, 14, 73, 85, 97 };
		System.out.println(Arrays.toString(merge(a, b)));
		System.out.println("done to take :" + ( System.nanoTime() - t1));
		
		long t2 = System.nanoTime();
		System.out.println(Arrays.toString(merge1(a, b)));
		System.out.println("done to take :" + ( System.nanoTime() - t2));
		
	}

}

package interview;

import java.io.BufferedReader;
import java.io.Console;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;

/*
 * 控制檯讀入
 方法一:使用new BufferedReader(new InputStreamReader(System.in))
 方法二:使用java.util.Scanner類 (JDK1.5引入)
 方法二:使用 java.io.Console類 (JDK1.6引入)
 */
public class ReadFromConsole {

	public void readFromBufferedReader() {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		String line = null;
		System.out.println("請輸入 	:>");
		try {
			while (!"Exit".equals(line = br.readLine())) {
				System.out.println("輸入的內容爲 = " + line);
				System.out.print("請輸入 :> ");
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		System.out.println("程序結束");
	}

	@SuppressWarnings("resource")
	public void readFromScanner() {
		Scanner scanner = new Scanner(System.in);
		String line = null;
		System.out.print("請輸入 :> ");
		while (!"exit".equals(line = scanner.nextLine())) {
			System.out.println("輸入的內容爲 = " + line);
			System.out.print("請輸入 :> ");
		}
		System.out.println("程序結束");
	}

	public void readFromConsole() {
		Console console = System.console();
		if (null == console) {
			System.out.println("Console爲null,不可用");
			System.exit(0);
		}
		String line = null;
		System.out.print("請輸入 :> ");
		while (!"Exit".equals(line = console.readLine())) {
			System.out.println("輸入的內容爲 = " + line);
			System.out.print("請輸入 :> ");
		}
		System.out.println("程序結束");
	}

	public static void main(String[] args) {
		ReadFromConsole test = new ReadFromConsole();
		test.readFromBufferedReader();
		test.readFromScanner();
		test.readFromConsole();
	}

}
package interview;

public class CharacterStatictics {

	public static void main(String[] args) {

		int chineseCharCount = 0;
		int spaceCount = 0;
		int digitCount = 0;
		int lettersCount = 0;
		int otherChars = 0;

		String value = "Hello world! Welcome to Java world! 1234567890 Java 字符統計個數小程序!";
		char[] chars = value.toCharArray();
		for (char c : chars) {
			if (isChineseCharacter(c)) {
				chineseCharCount++;
			} else if (Character.isLetter(c)) {
				lettersCount++;
			} else if (Character.isDigit(c)) {
				digitCount++;
			} else if (' ' == c) {
				spaceCount++;
			} else {
				otherChars++;
			}
		}

		System.out.println("中文字符:" + chineseCharCount);
		System.out.println("數字:" + digitCount);
		System.out.println("字母:" + lettersCount);
		System.out.println("空格:" + spaceCount);
		System.out.println("其它字符:" + otherChars);

	}

	private static boolean isChineseCharacter(char c) {
		return c >= '\u4E00' && c <= '\u9FBF';
	}

}

package interview;
/**
 * 兩個線程陷入死鎖
 * @author xl
 *
 */
public class DeadlockExample {

	String resource1 = "資源1";
	String resource2 = "資源2";
	Thread t1 = new Thread("線程1") {
		public void run() {
			while (true) {
				synchronized (resource1) {
					synchronized (resource2) {
						System.out.printf("線程1擁有[%s], 需要[%s]\n", resource1,
								resource2);
					}
				}
			}
		}
	};
	Thread t2 = new Thread("線程2") {
		public void run() {
			while (true) {
				synchronized (resource2) {
					synchronized (resource1) {
						System.out.printf("線程2擁有[%s], 需要[%s]\n", resource2,
								resource1);
					}
				}
			}
		}
	};

	public static void main(String a[]) {
		DeadlockExample test = new DeadlockExample();
		test.t1.start();
		test.t2.start();
	}

}




發佈了46 篇原創文章 · 獲贊 5 · 訪問量 11萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章