面试题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();
}
}
}