在这个程序中,提出了if-statement,它必须从另一个类名为Studentfactory的类中调用。
public class Control {
public static void main(String[] args) {
Student[] studs = new Student[3];
for (int i = 0; i < 3; i++) {
studs[i] = createStudent();
}
for (int i = 0; i < 3; i++) {
System.out.println(studs[i]);
}
}
static Student createStudent() {
Scanner sc = new Scanner(System.in);
System.out.print("Enter your name:");
String name = sc.nextLine();
System.out.print("Enter your age:");
int age = sc.nextInt();
if(age <20) {
return new JuniorStudent(name, age);
} else if( age < 30) {
return new IntermediateStudent(name,age);
}
return new SeniorStudent(name, age);
}
}
// if语句必须从此类调用
package demo;
public class Studentfactory {
}
答案 0 :(得分:2)
&#34; if-statement&#34; interface
将是Predicate
,在您的情况下可能是Predicate<Integer>
。你可以做点什么
class AgePredicates {
public static final Predicate<Integer> isJunior = a -> a < 20;
public static final Predicate<Integer> isIntermediate = a -> a > 20 && a < 30;
public static final Predicate<Integer> isSenior = a -> a >= 30;
}
然后&#34;从另一个班级打电话给他们&#34;由
if (AgePredicates.isJunior.test(age)) {
// ...
} else if (AgePredicates.isIntermediate.test(age)) {
// ...
} else {
// ...
}
答案 1 :(得分:1)
如果我理解正确,您想从类createStudent
Control
的静态方法StudentFactory
这样做的方法是
Control.createStudent()
(在班级StudentFactory
)
希望这有帮助!
答案 2 :(得分:0)
您可以做的是在方法中将Student
的年龄作为参数:
static Student createStudent(int age) { // note the parameter here
Scanner sc = new Scanner(System.in);
System.out.print("Enter your name:");
String name = sc.nextLine();
// no sc.nextInt() here anymore
if(age <20) {
return new JuniorStudent(name, age);
} else if( age < 30) {
return new IntermediateStudent(name,age);
}
return new SeniorStudent(name, age);
}
通过执行此操作,您可以从其他位置的命令行读取下一个整数,并使用下一个int作为参数调用该方法。然后该方法决定要创建哪种学生。
<强>更新强>
在您提供的其他课程中,您可以从任何地方获取年龄(命令行,最有可能),然后将其用作以下参数:
public class Studentfactory {
public Student createStudentByControl() {
// create a new Control object
Control control = new Control();
// get the age from command line
int age = sc.nextInt();
// use the age as parameter for the control to create a new student
Student student = control.createStudent(age);
return student;
}
}