面試題1:獲得兩個字符串的最大子串
/**
* 假設:兩個字符串中只有一個最大相同子串
* @param str1
* @param str2
* @return
*/
public String getMaxSameString(String str1, String str2) {
if (str1 != null && str2 != null) {
String maxStr = (str1.length() >= str2.length()) ? str1 : str2;
String minStr = (str1.length() < str2.length()) ? str1 : str2;
int length = minStr.length();
for (int i = 0; i < length; i++) {
for (int x = 0, y = length - i; y <= length; x++, y++) {
String subStr = minStr.substring(x, y);
if (maxStr.contains(subStr)) {
return subStr;
}
}
}
}
return null;
}
面試題2:
/**
* note:
* 1.區分List中remove(int index)和remove(Object obj)
* 2.IDEA中好像會判斷是不是index.. List類型時,無法自動裝箱;只會將2認定爲index
* 3.下面的變量聲明的是List,所以會判斷。但是如果是Collection類型的話,只有remove(object)函數,所以會自動裝箱。
*/
public class ListExer {
@Test
public void testListRemove() {
List list = new ArrayList();
list.add(1);
list.add(2);
list.add(3);
updateList(list);
System.out.println(list);
}
/**
* 第一個是刪除 index爲2的數值
* 第二個是刪除 對象2
* @param list
*/
private void updateList(List list) {
list.remove(2);
list.remove(new Integer(2));
}
}
面試題3:
/**
* @author shkstart
* @create 2019 上午 9:36
*
* note:Person中已經重寫equals和hashcode方法
* 1.remove失敗:remove的原理,和add一樣,同樣會計算hashcode
* remove移除失敗原因:修改對象後的hashcode變了。
* 2.添加成功,new Person(1001,"CC")通過hashcode計算的座標值上沒有數據
* 3.添加成功,座標已有數據,但是hash值不同
*/
public class CollectionTest {
@Test
public void test3(){
HashSet set = new HashSet();
Person p1 = new Person(1001,"AA");
Person p2 = new Person(1002,"BB");
set.add(p1);
set.add(p2);
System.out.println(set);
p1.name = "CC";
set.remove(p1);
System.out.println(set);
set.add(new Person(1001,"CC"));
System.out.println(set);
set.add(new Person(1001,"AA"));
System.out.println(set);
}
}
輸出結果:
[Person{id=1002, name='BB'}, Person{id=1001, name='AA'}]
[Person{id=1002, name='BB'}, Person{id=1001, name='CC'}]
[Person{id=1002, name='BB'}, Person{id=1001, name='CC'}, Person{id=1001, name='CC'}]
[Person{id=1002, name='BB'}, Person{id=1001, name='CC'}, Person{id=1001, name='CC'}, Person{id=1001, name='AA'}]
練習題1
/**
* 課後練習2:判斷指定目錄下是否有後綴名爲.jpg的文件,如果有,就輸出該文件名稱
* @author shkstart 郵箱:[email protected]
* @version 創建時間:2019年2月23日 上午1:55:59
*
*/
public class FindJPGFileTest {
@Test
public void test1(){
File srcFile = new File("d:\\code");
File[] listFiles = srcFile.listFiles();
for(File file : listFiles){
if(file.getName().endsWith(".jpg")){
System.out.println(file.getAbsolutePath());
}
}
}
/*
* File類提供了兩個文件過濾器方法
* public String[] list(FilenameFilter filter)
* public File[] listFiles(FileFilter filter)
*/
@Test
public void test2(){
File srcFile = new File("d:\\code");
File[] subFiles = srcFile.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.endsWith(".jpg");
}
});
for(File file : subFiles){
System.out.println(file.getAbsolutePath());
}
}
}
練習題2
/**
*問題:遍歷指定目錄所有文件名稱,包括子文件目錄中的文件。
* 拓展1:並計算指定目錄佔用空間的大小
* 拓展2:刪除指定文件目錄及其下的所有文件
*
* @author shkstart 郵箱:[email protected]
* @version 創建時間:2019年2月23日 上午1:55:31
*
*/
public class ListFilesTest {
public static void main(String[] args) {
File dir = new File("d:\\code");
printSubFile(dir);
int allCount = getAllSubFile(dir);
System.out.println(allCount);
}
/**
* 這是自己寫的方法
* 1.遞歸方法列出該目錄下的所有文件
* 2.並計算文件個數
* @param dir
* @return
*/
public static int getAllSubFile(File dir) {
int count = 0;
if (dir.isFile()){
System.out.println(dir);
count++;
}else {
File[] subfiles = dir.listFiles();
for (File f:subfiles){
count = count + getAllSubFile(f);
}
}
return count;
}
/**
* 遞歸方法列出該目錄下的所有文件
* @param dir
*/
public static void printSubFile(File dir) {
File[] subfiles = dir.listFiles();
for (File f : subfiles) {
if (f.isDirectory()) {
printSubFile(f);
} else {
System.out.println(f.getAbsolutePath());
}
}
}
/**
* 拓展1:求指定目錄所在空間的大小,求任意一個目錄的總大小
* 1.file是文件,那麼直接返回file.length()
* 2.file是目錄,把它的下一級的所有大小加起來就是它的總大小
*
* @param file
* @return
*/
public long getDirectorySize(File file) {
long size = 0;
if (file.isFile()) {
size += file.length();
} else {
File[] all = file.listFiles();
for (File f : all) {
size += getDirectorySize(f);
}
}
return size;
}
/**
* 拓展2:刪除指定的目錄
* 1.如果file是文件,直接delete
* 2.如果file是目錄,先把它的下一級幹掉,然後刪除自己
* 3.循環刪除的是file的下一級
* @param file
*/
public void deleteDirectory(File file) {
if (file.isDirectory()) {
File[] all = file.listFiles();
for (File f : all) {
deleteDirectory(f);
}
}
file.delete();
}
}
關於流的幾個問題:
/**
* 1.System.in:標準的輸入流,默認從鍵盤輸入
* System.out:標準的輸出流,默認從控制檯輸出
* 2.練習:從鍵盤輸入字符串,要求將讀取到的整行字符串轉成大寫輸出。
* 然後繼續進行輸入操作,直至當輸入“e”或者“exit”時,退出程序。
* @throws Exception
*/
public static void main(String[] args) throws IOException {
InputStreamReader streamReader = new InputStreamReader(System.in);
BufferedReader reader = new BufferedReader(streamReader);
while (true) {
System.out.print("請輸入字符串:");
String data = reader.readLine();
if ("e".equalsIgnoreCase(data) || "exit".equalsIgnoreCase(data)) {
System.out.println("程序結束!");
break;
}
String upperCase = data.toUpperCase();
System.out.println(upperCase);
}
reader.close();
}
更改輸出方向:
/**
* 打印流:PrintStream 和PrintWriter
* 更改輸出方向:控制檯--->文件
*/
@Test
public void test() throws Exception {
FileOutputStream fileOutput = new FileOutputStream("result.txt");
PrintStream printStream = new PrintStream(fileOutput, true);
/**
* 創建打印輸出流,設置爲自動刷新模式(寫入換行符或字節 '\n' 時都會刷新輸出緩衝區)
*/
if (printStream != null) {
System.setOut(printStream);
}
for (int i = 0; i <= 255; i++) {
System.out.print((char) i);
if (i % 50 == 0) {
System.out.println();
}
}
printStream.close();
}
實現scanner功能:
public class MyInput {
// Read a string from the keyboard
public static String readString() {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
// Declare and initialize the string
String string = "";
// Get the string from the keyboard
try {
string = br.readLine();
} catch (IOException ex) {
System.out.println(ex);
}
// Return the string obtained from the keyboard
return string;
}
// Read an int value from the keyboard
public static int readInt() {
return Integer.parseInt(readString());
}
// Read a double value from the keyboard
public static double readDouble() {
return Double.parseDouble(readString());
}
// Read a byte value from the keyboard
public static double readByte() {
return Byte.parseByte(readString());
}
// Read a short value from the keyboard
public static double readShort() {
return Short.parseShort(readString());
}
// Read a long value from the keyboard
public static double readLong() {
return Long.parseLong(readString());
}
// Read a float value from the keyboard
public static double readFloat() {
return Float.parseFloat(readString());
}
}
練習題:統計字符種類
/**
* 練習3:獲取文本上字符出現的次數,把數據寫入文件
*
* 思路:
* 1.遍歷文本每一個字符
* 2.字符出現的次數存在Map中
*
* Map<Character,Integer> map = new HashMap<>();
* map.put('a',18);
* map.put('你',2);
*
* 3.把map中的數據寫入文件
*
* @author shkstart
* @create 2019 下午 3:47
*/
public class WordCount {
@Test
public void testWordCount() throws Exception{
Map<Character, Integer> map = new HashMap<>();
FileReader fr = new FileReader("dbcp.txt");
int c; //讀取字符,但是是以int的形式返回;因此需要強轉會char
while ((c = fr.read()) != -1) {
char ch = (char) c;
// 判斷char是否在map中第一次出現
if (map.get(ch) == null) {
map.put(ch, 1);
} else {
map.put(ch, map.get(ch) + 1);
}
}
/**
* 統計結束之後,將map中的內容寫入到txt文件中
*/
BufferedWriter bw = new BufferedWriter(new FileWriter("wordcount.txt"));
Set<Map.Entry<Character, Integer>> entrySet = map.entrySet();
for (Map.Entry<Character, Integer> entry : entrySet) {
switch (entry.getKey()) {
case ' ':
bw.write("空格=" + entry.getValue());
break;
case '\t'://\t表示tab 鍵字符
bw.write("tab鍵=" + entry.getValue());
break;
case '\r'://
bw.write("回車=" + entry.getValue());
break;
case '\n'://
bw.write("換行=" + entry.getValue());
break;
default:
bw.write(entry.getKey() + "=" + entry.getValue());
break;
}
bw.newLine();
}
}
}