(100分)if else 很多怎么办????有什么替代的!(主要是字符串判断)

lookhang 2009-08-17 11:33:44
if else 很多怎么办????有什么替代的!(主要是字符串判断)

if(str.equal("1")){

}else if(str.equal("1")){

}else if(str.equal("1")){

}else .......


太多了!写得我没话说了!
...全文
1473 105 打赏 收藏 转发到动态 举报
写回复
用AI写文章
105 条回复
切换为时间正序
请发表友善的回复…
发表回复
APOLLO_TS 2009-08-19
  • 打赏
  • 举报
回复
典型因果结构--可以变成单点结构
ref, method
download ,com.xxx.下载方法名
一个hashmap存储。
dealWith(PContext p){
在定值列表中反射结果方法就行了。
}

要是采用JDK7.0你可以自己装配。
ansj 2009-08-19
  • 打赏
  • 举报
回复
反射慢
chenchuanfeng001 2009-08-19
  • 打赏
  • 举报
回复
[Quote=引用 87 楼 ansjsun 的回复:]

而且告诉你个秘密

java里面if (){} if (){} if (){} if (){} if (){} if (){}
和 if(){} else if{} else if{} else if{} else if{} else if{}
没有区别的..这样如果你不用switch..他会给你从头比到尾的....
[/Quote]
这可能一样吗?像这句

if(a==1){;}
else if(b==1){;}

应该是等价于。

if(a==1){;}
if(a!=1&&b==1){;}
wangan200808 2009-08-19
  • 打赏
  • 举报
回复
[Quote=引用 100 楼 welllit 的回复:]
Map m = new HashMap();
m.put("download","下载");
m.put("upload","上传");
...
m.put("sort","排序");

Iterator ite = m.keySet().iterator();
while(ite.hasNext()){
String key = (String)ite.next();
if cmd.equals(key){
  log.info(m.get(key).toString());
  break;
}
[/Quote]
可以借助这个思路,map的值为方法名称或参数,调用不同的方法,或者向同一个方法传递不同的参数,避免出现太多的if else
hjy273 2009-08-19
  • 打赏
  • 举报
回复
用个表示cmd的字符串数组,然后再用switch-case方法可行。或者有更好的方法,摸索中学习。--加油
welllit 2009-08-19
  • 打赏
  • 举报
回复
Map m = new HashMap();
m.put("download","下载");
m.put("upload","上传");
...
m.put("sort","排序");

Iterator ite = m.keySet().iterator();
while(ite.hasNext()){
String key = (String)ite.next();
if cmd.equals(key){
log.info(m.get(key).toString());
break;
}
Pbulic 2009-08-19
  • 打赏
  • 举报
回复

Map m = new HashMap();
m.put("download","下载");
m.put("upload","上传");
...
m.put("sort","排序");
Iterator ite = m.keySet().iterator();
while (ite.hasNext()) {
String key = (String)ite.next();
if (cmd.equals(key)) {
log.info(m.get(key).toString());
break;
}
}
lookhang 2009-08-19
  • 打赏
  • 举报
回复
[Quote=引用 95 楼 yywl62 的回复:]
看来你的Struts没学好啊,直接用DispatchAction不就得了,将parameter配置为cmd
调用直接就是xxx.do?cmd=命令
或者自己写个Action,支持 xxx/命令.do格式的不就行了,这么麻烦啊
[/Quote]

呃~~~注意看这个,我用的就是DispatchAction,自定义的Action方法command:
public ActionForward command(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws IOException {

String cmd=request.getParameter("cmd").trim();//指令名,对应CommandProcess中的方法名
/*
* 指令列表
* 下载文件:cmd=download&file=product/mlns/C053.gif&userid=1
* 注册:cmd=register
* 登陆:cmd=login&userid=1&psw=jh45dd
* 修改密码:cmd=changePsw&userid=1&oldpswjh45dd&newpsw=kl8547
*/
CommandProcess commandProcess=new CommandProcess(request,response);
Method method = null;
try {
method = commandProcess.getClass().getMethod(cmd);
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
log.info("找不到名为"+cmd+"的方法!请注意大小写!"+e.getMessage());
}
try {
method.invoke(commandProcess);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}


我说的是在方法里面怎么避免大量的if else语句,如果都用DispatchAction中的方法更不好吧~~
why_java 2009-08-19
  • 打赏
  • 举报
回复
假如参数相同
用函数调用吧!
小灰狼 2009-08-19
  • 打赏
  • 举报
回复
业务逻辑上有那么多判断,代码就要写那么多,这一点你跑不掉的,代码不可能少得了

如果要灵活的话,可以用反射,先建立一个被判断的字符串值和被调用的方法之间的映射,然后判断语句写一两行就可以了
kevin-yy 2009-08-19
  • 打赏
  • 举报
回复
看来你的Struts没学好啊,直接用DispatchAction不就得了,将parameter配置为cmd
调用直接就是xxx.do?cmd=命令
或者自己写个Action,支持 xxx/命令.do格式的不就行了,这么麻烦啊

[Quote=引用 83 楼 sixme 的回复:]
决定用反射了~Java codepublic ActionForward command(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)throws IOException {

String cmd=request.getParameter("cmd").trim();//指令名,对应CommandProcess中的方法名/*
* 指令列表
* 下载文件:cmd=download&file=product/mlns/C053.gif&userid=1
* 注册:cmd=register
* 登陆:cmd=login&userid=1&psw=jh45dd
* 修改密码:cmd=changePsw&userid=1&oldpswjh45dd&newpsw=kl8547*/
CommandProcess commandProcess=new CommandProcess(request,response);
Method method=null;try {
method= commandProcess.getClass().getMethod(cmd);
}catch (SecurityException e) {// TODO Auto-generated catch block e.printStackTrace();
}catch (NoSuchMethodException e) {// TODO Auto-generated catch block log.info("找不到名为"+cmd+"的方法!请注意大小写!"+e.getMessage());
}try {
method.invoke(commandProcess);
}catch (IllegalArgumentException e) {// TODO Auto-generated catch block e.printStackTrace();
}catch (IllegalAccessException e) {// TODO Auto-generated catch block e.printStackTrace();
}catch (InvocationTargetException e) {// TODO Auto-generated catch block e.printStackTrace();
}returnnull;
}

Java codeimport java.io.IOException;import java.util.HashMap;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.apache.log4j.Logger;import com.iwit.noteService.bean.User;import com.iwit.noteService.dao.DaoFactory;import com.iwit.noteService.util.FunctionUtil;/**
*
*@author luhang E-mail:sixer@126.com
*@version 创建时间:Aug 18, 2009 11:46:33 AM
**/publicclass CommandProcess {
Logger log= Logger.getLogger(CommandProcess.class);
HashMap<String,String> configs=DaoFactory.getConfigDao().getAllConfig();
HttpServletRequest request;
HttpServletResponse response;public CommandProcess(HttpServletRequest request,
HttpServletResponse response) {super();this.request= request;this.response= response;
}/**
*
*下载文件
*@return 路径*/publicvoid download(){
String result="Failure";try {int userid=Integer.parseInt(request.getParameter("userid"));
result=configs.get("download_url")+request.getParameter("file");
}catch (NumberFormatException e) {// TODO: handle exception }try {
response.getWriter().write(result);
}catch (IOException e) {// TODO Auto-generated catch block log.info("Web相应异常!"+e.getMessage());
}
}/**
* 用户注册
*@return ID+PSW*/publicvoid register(){
String result="Failure";
String timmill=System.currentTimeMillis()+"";
String psw=FunctionUtil.GenerateRandomStr();
User user=new User(FunctionUtil.EncoderByMd5(psw),timmill);if(DaoFactory.getUserDao().insertUser(user)){
log.debug("新用户注册成功!");
user=DaoFactory.getUserDao().getNewUserByRemark(timmill);
result=user.getU_id()+"+"+psw;
}else{
log.info("新用户注册失败!");
}try {
response.getWriter().write(result);
}catch (IOException e) {// TODO Auto-generated catch block log.info("Web相应异常!"+e.getMessage());
}
}publicvoid login(){
String result="Failure";try {int userid=Integer.parseInt(request.getParameter("userid"));
String psw=request.getParameter("psw");
User user=DaoFactory.getUserDao().getUserById(userid);if(user.getU_psw().equals(FunctionUtil.EncoderByMd5(psw))){
log.debug("ID:"+userid+"登陆成功!");
result="Logined";
}else{
log.info("ID:"+userid+"登陆失败,密码错误!");
}
}catch (NumberFormatException e) {// TODO: handle exception log.info("非法的用户ID!"+e.getMessage());
}try {
response.getWriter().write(result);
}catch (IOException e) {// TODO Auto-generated catch block log.info("Web相应异常!"+e.getMessage());
}
}publicvoid changePsw(){
String result="Failure";try {int userid=Integer.parseInt(request.getParameter("userid"));
String oldPsw=request.getParameter("oldpsw");
User user=DaoFactory.getUserDao().getUserById(userid);if(user.getU_psw().equals(FunctionUtil.EncoderByMd5(oldPsw))){
String newPsw=request.getParameter("newpsw");
user.setU_psw(FunctionUtil.EncoderByMd5(newPsw));if(DaoFactory.getUserDao().updateUser(user)){
log.debug("ID:"+userid+"密码修改成功!");
result="PswChanged";
}else{
log.debug("ID:"+userid+"密码修改失败!");
}
}else{
log.info("ID:"+userid+"旧密码错误!");
}
}catch (NumberFormatException e) {// TODO: handle exception log.info("非法的用户ID!"+e.getMessage());
}try {
response.getWriter().write(result);
}catch (IOException e) {// TODO Auto-generated catch block log.info("Web相应异常!"+e.getMessage());
}
}//下面还有好多方法........}
[/Quote]
flyyuyr 2009-08-19
  • 打赏
  • 举报
回复
可以试试switch
wow415411408 2009-08-18
  • 打赏
  • 举报
回复
字符串 还这么多 当然选择switch啦
楼上有很多好意见了 用map或者枚举 看楼主喜好了
街头小贩 2009-08-18
  • 打赏
  • 举报
回复
超过三层if...else就要用switch,如果还是很多表明你的设计有问题
pushme 2009-08-18
  • 打赏
  • 举报
回复
学习学习。
Yedy2000 2009-08-18
  • 打赏
  • 举报
回复
反射效率也不高
awusoft 2009-08-18
  • 打赏
  • 举报
回复
这样的感觉就if else嘛~~还想那么多干什么呢,最多是下边的业务代码放到一个方法中去啊.
if()
方法一
else if
方法二
.....
kingarden 2009-08-18
  • 打赏
  • 举报
回复
定义个枚举类型,然后通过switch...case对不同的枚举做对应的处理。
qsrock 2009-08-18
  • 打赏
  • 举报
回复
[Quote=引用 54 楼 sixme 的回复:]
引用 53 楼 qsrock 的回复:
引用 52 楼 sixme 的回复:
多态行不通啊,因为方法的参数列表可能是相同的,但业务不同!

写个接口,每个实现接口类都对应一个算法(就是你现在的一个判断);
如果多一种判断你就写多一个类!不需要改原来的东西!好坏就自己权衡!


你的意思是这样?
Java codepublicinterface Myfunction{

}publicclass Download implement Myfunction{

}publicclass Register implement Myfunction{

}
......//以下省略

但是我怎样才能在收到cmd的时候选择不通的类啊?
[/Quote]
可以通过反射!
die_angle 2009-08-18
  • 打赏
  • 举报
回复
可以把你的东西放到一个集合里,这样只要在使用时遍历就可以了
加载更多回复(85)

62,615

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧