这个是我入第二家公司,技术总监面试的一道我认为有水平的java面试题,当时我心里没有准确的答案,在一知半懂的情况下答了出了。结果是我面试上了。后来这道题成为了我面试别人是否能录用的标准之一,因为这也是java基础。
我们一般的问法是这样:在一个门户网站,且没有登录的情况下要如何统计出在线人数。很多人给我的答案大多是拦首页等或别的页面,当然这个是不行的。还有的答法是用过滤器,这个或许可以,但至今我没有试过。
我们给出的代码是使用session的监听器,因为我们知道一连接一个用户,就会产生一个新的session。而断开一个用户则会销毁一个session。我们分别在产生和销毁时对在线用户数加1或是-1。这样的数据与当前用户数大致相同。说大致相同是因为session的销毁要在用户退出后的一段时间。所以会造成一定的偏差。
代码大致如下:
package com.buyli.interview;
/**
* @Copyright @ 2012
* All right reserved
* @version 创建时间:Created on 2012-10-19
* @author 作者:Create by www.360buyli.com
* @Email: 360buyli@gmail.com
* @description eclipse注释模板
*/
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Word {
// 查找其中字符串"me"单词的数量
private static final String matcherStr = "me";
public static void main(String[] args) {
System.out.println("方法2查找到的数量为:"+getWordCount2());
}
//这个方式依赖于各个单词之间是空格隔开的
public int getWordCount1(){
try {
String content="me hello me me me me me me";
Pattern expression = Pattern.compile("[a-zA-Z]+");
Matcher matcher = expression.matcher(content.toString().toLowerCase());
int i = 0;
while (matcher.find()) {
if (matcher.group().toLowerCase()
.equals(matcherStr.toLowerCase())) {
i++;
}
}
System.out.println("此单词的数量是:" + i + "个");
return i;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
//不需要空格隔开,查到一个之后,索引从下一个开始
public static int getWordCount2(){
try {
String content="mehellomemememememe";
int i=0;
int index=0;
boolean bool=true;
while(bool){
int currentIndex=content.indexOf(matcherStr, index);
System.out.println(currentIndex);
if(currentIndex>=0){
index=currentIndex+1;
i=i+1;
}else{
bool=false;
}
}
return i;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
}