你好我有一些我正在制作的程序的while语句,并且每个语句在另一个类中定义了不同的setMethod但是我想以更紧凑的方式执行此操作。我想知道是否某种循环可以做到这一点。或者,如果你有一个setMethod数组。或任何能使这段代码变得紧凑的东西。
contestant1是班级参赛者信息的对象,其中包含每个领域的设定方法。
do {
try {
flag = false;
System.out.println("Please enter your first name.");
String firstName = Scanner.nextLine();
contestant1.setName(firstName);
} catch (InvalidInputException e) {
System.out.println(e.getMessage());
flag = true;
}
} while (flag);
do {
try {
flag = false;
System.out.println("Please enter your last name.");
String lastName = Scanner.nextLine();
contestant1.setLastName(lastName);
} catch (InvalidInputException e) {
System.out.println(e.getMessage());
flag = true;
}
} while (flag);
do {
try {
flag = false;
System.out.println("Please enter your street number.");
String streetNumber = Scanner.nextLine();
contestant1.setStreetNumber(streetNumber);
} catch (InvalidInputException e) {
System.out.println(e.getMessage());
flag = true;
}
} while (flag);
答案 0 :(得分:3)
String[] setMethodNames={"FirstName","LastName","Street"};
Class cls = Class.forName("<qualifiedname>Contestant");
Class parameterTypes = String.class;
for(String s:setMethodNames){
do{
try{
flag=false;
System.out.println("Please enter your "+s+" :");
String inp=scanner.nextLine();
cls.getDeclaredMethod("set"+s, parameterTypes ).invoke(contestant1, inp);
}catch(InvalidInputException e){
System.out.println(e.getMessage());
flag = true;
}
}while(flag);
}
您还可以使用反射和调用setter
答案 1 :(得分:1)
String[] setMethodNames={"First Name","Last Name","Street"};
for(String s:setMethodNames){
do{
try{
flag=false;
System.out.println("Please enter your "+s+" :");
String inp=scanner.nextLine();
callSetFunction(contestant1,s,inp);
}catch(InvalidInputException e){
System.out.println(e.getMessage());
flag = true;
}
}while(flag)
}
private void callSetFunction(Contestant contestant1,String s,String inp){
switch(s){
case "First Name":
contestant1.setFirstName(inp);
break
case "Last Name":
contestant1.setLastName(inp);
break;
case "Street":
contestant1.setStreet(inp);
break;
default:
//do something
}
}
答案 2 :(得分:1)
如果你正在使用Java 8,你可以这样做:
List<String> labels = Arrays.asList(
"Please enter your first name.",
"Please enter your last name.",
"Please enter your street number."
);
Function<String, Void> setters = Arrays.asList(
contestant1::setName,
contestant1::setLastName,
contestant1::setStreetNumber
);
Iterator<String> label = labels.iterator();
for(Function<String, Void> setter : setters) {
do {
try {
flag = false;
System.out.println(label.next());
String value = Scanner.nextLine();
setter.apply(value);
} catch (InvalidInputException e) {
System.out.println(e.getMessage());
flag = true;
}
} while (flag);
}