我有一些类似UniversityDepartment
& PolytechnicDepartment
这两个类扩展了AcademicDepartment
类。问题要我这样做。 AcademicDepartment
可以有研究生课程&研究生课程。部门将是2 University
& Polytechnic
。根据研究生课程中的实验室数量,对于理工学院或大学的部门。因此,如果我们在研究生或研究生课程,我认为用户必须从键盘输入,如果我们在研究生,我们也必须被问到,如果我们在理工学院或大学,我们有多少实验室。那么我将如何做到这一点?我将举例说明我的代码:
import java.io.*;
public class AcademicDepartment {
private String names;
private String labs;
private int teachers;
private int graduates;
// private boolean studies;
public void infostudies() throws IOException{
System.out.println("Enter the department you want."
+ "Press 1 for pre-graduate program or 2 for after-graduate program" );
String studies = "";
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
studies = br.readLine();
if (studies == 1){
System.out.println("You are in pre-graduate program");
System.out.println("Enter the number of labs");
String labs = "";
BufferedReader br1 = new BufferedReader(new InputStreamReader(System.in));
labs = br1.readLine();
if (labs > 5){
System.out.println("The department is polytechnic");
}
}
if (labs < 5 ){
System.out.println("The department is University");
}
else
{
System.out.println("Wrong number try again");
}
}
public AcademicDepartment(String names,String labs,int teachers,int graduates){
names = new String(names);
this.labs = labs;
this.teachers = teachers;
this.graduates = graduates;
}
public void printdepartmentinfo(){
System.out.println("The names are:" + names);
System.out.println("The labs are:" + labs);
System.out.println("The GRADUATES are:" + graduates);
System.out.println("The teachers are:" + teachers);
}
}
答案 0 :(得分:0)
关于代码,有一些不幸的事情。
一个问题是您将字符串变量studies
和labs
与整数文字进行比较。编译器不允许这样做。通常,可以将String变量(使用String.equals
)与String文字进行比较,或者在与整数进行比较之前尝试使用Integer.parseInt
解释String变量。
另一个问题是方法infostudies
的一些局部变量与类AcademicDepartment
的字段具有相同的名称。这是允许的,但它不必要地混淆。
举个例子,你将处理变量studies
,但我会告诉你我对变量labs
的意思。
不要这样做:
public class AcademicDepartment {
...
public void infostudies() throws IOException {
...
if (studies == 1) {
...
String labs = "";
...
if (labs > 5){ // Compare String with int? Won't compile!
...
}
...
}
if (labs < 5) { // Can't see the "labs" defined above!
...
}
...
}
}
这样做:
public class AcademicDepartment {
...
public void infostudies() throws IOException {
...
if (studies == 1) {
...
String labs = "";
...
try {
int labCount = Integer.parseInt(labs);
if (labCount > 5) {
System.out.println("The department is polytechnic");
} else {
System.out.println("The department is University");
}
} catch (NumberFormatException formatErr) {
System.out.println("Sorry, couldn't understand your number of labs.");
}
...
}
...
}
}