我想输进来“1”,就执行a1方法,输进来“2”,就执行a2方法,怎么弄?根据方法名做判断
有很多个这样的方法,不想一个一个写
str.contains("");
如果函数签名不一样可以用重载,也可以用switch判断输入数字,执行不同方法
switch str.contains("")
case 1
case 2
switch(expression){
case constant-expression :
statement(s);
break; // 可选的
case constant-expression :
statement(s);
break; // 可选的
// 您可以有任意数量的 case 语句
default : // 可选的
statement(s);
}
从设计结构上找原因,问题不在于你的设想实现不了,而是在于你的设计模式。
不嫌麻烦的话用反射可以实现你所需要的效果:
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.InvocationTargetException;
public class Test {
public void a1() {
System.out.println("a1");
}
public void a2() {
System.out.println("a2");
}
public void ax() {
System.out.println("ax");
}
// 根据传入的名字来执行方法
public static void executeMethode(String methodeName) throws NoSuchFieldException, NoSuchMethodException,IllegalAccessException, InvocationTargetException{
Test test = new Test();
Class testClass = Test.class;
Method method = testClass.getDeclaredMethod("a"+methodeName);
method.invoke(test);
}
public static void main(String []args) throws NoSuchFieldException, NoSuchMethodException, IllegalAccessException, InvocationTargetException{
executeMethode("1");
}
}
可以查看JAVA的反射机制
感觉你应该是初学者,用switch比较好。 深入点用设计模式,反射。
int a=in.nextint;
if(a==1){
do a1;
}
else if(a==2){
do a2;
}
是这样?