一、遞歸遍歷文件夾
package com.cjhk.listenner;
import java.io.File;
import java.io.FilenameFilter;
import java.util.List;
public class FileNameList {
//使用遞歸實現的
public void listFileName(String filepath) {
File file = new File(filepath);
File[] files = file.listFiles();
for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory()) {
FileNameList flist = new FileNameList();
flist.listFileName(files[i].getAbsolutePath());
System.out.println("Directory:" + files[i].getName());
} else {
System.out.println("File:" + files[i].getName());
}
}
}
public FileNameList() {
}
public static void main(String[] args) {
FileNameList fl = new FileNameList();
fl.listFileName("F://有用//Ajax");
}
}
二、斐波那契數列
public class feibo {
public static void main(String[] args) {
int n = 8;
int[] s = new int[n];
s[0] = 1;
s[1] = 1;
for (int i = 2; i < n; i++) {
s[i] = s[0] + s[1];
s[0] = s[1];
s[1] = s[i];
}
System.out.println("第" + n + "位的值是:" + s[n - 1]);
}
}
三、迴文
public class huiwen {
public static void main(String[] args) {
String ms="是迴文";
String s = "0000";
char[] c = s.toCharArray();
int len = c.length;
for (int i = 0, j = len - 1; i < len && j > 0; i++, j--) {
if (c[i] != c[j]) {
ms="不是迴文";
break;
}
}
System.out.println(ms);
}
}
四、逆向輸出
public class tset {
public static void main(String[] args) {
System.out.println(get(654321));
}
public static int get(int a) {
String s = Integer.toString(a);
char[] c = s.toCharArray();
char[] t = new char[c.length];
for (int i = c.length - 1, j = 0; i >= 0 && j < c.length; i--, j++) {
t[j] = c[i];
}
String st = new String(t);
return Integer.parseInt(st);
}
}
五、排序
public class Sort {
public static void main(String[] args) {
int[] a = { 1, 45, 6, 9, 78, 36, 5 };
maopao(a);
for (int i = 0; i < a.length; i++) {
System.out.println(a[i]);
}
}
/** 冒泡排序 */
public static void maopao(int[] a) {
for (int i = 0; i < a.length - 1; i++) {
for (int j = 0; j < a.length - 1 - i; j++) {
if (a[j] > a[j + 1]) {
int t = a[j + 1];
a[j + 1] = a[j];
a[j] = t;
}
}
}
}
}
六、設計4個線程,其中兩個線程每次對j增加1,另外兩個線程對j每次減少1
package com.test1;
/**設計4個線程,其中兩個線程每次對j增加1,另外兩個線程對j每次減少1*/
public class ThreadTest {
private int j;
public static void main(String[] args) {
ThreadTest threadtest = new ThreadTest();
Inc inc = threadtest.new Inc();
Dec dec = threadtest.new Dec();
for (int i = 0; i < 2; i++) {
Thread t = new Thread(inc);
t.start();
t = new Thread(dec);
t.start();
}
}
private synchronized void inc() {
j++;
System.out.println(Thread.currentThread().getName() + "-inc:" + j);
}
private synchronized void dec() {
j--;
System.out.println(Thread.currentThread().getName() + "-dec:" + j);
}
class Inc implements Runnable {
public void run() {
for (int i = 0; i < 100; i++) {
inc();
}
}
}
class Dec implements Runnable {
public void run() {
for (int i = 0; i < 100; i++) {
dec();
}
}
}
}