我可以尝试在 setter 中捕获异常吗?如果是这样,我该如何正确执行此操作?



我想发生的是让用户输入年龄并让程序使用 getter 和 setter,同时检查异常,如果它确实捕获异常,它将不得不再次运行该方法。

import java.util.Scanner;

公共类 主 {

public static void main(String[] args) {
Scanner in = new Scanner(System.in);
TestPatient patientZero = new TestPatient();
patientZero.setAge(in.nextInt());
System.out.println(patientZero.getAge());
}
}

//患者类

import java.util.InputMismatchException; import java.util.Scanner;

公开课 测试患者 { 私人 int 年龄;

public int getAge(){
return age;
}
public void setAge(int newAge){
Scanner in = new Scanner(System.in);
int age;
boolean success = false;
try {
System.out.print("Enter in Your age:");
age = in.nextInt();
success = true;
} catch (InputMismatchException ex) {
System.out.println("Im sorry, please enter just you age.nTry again");
}
this.age=newAge;
}

}

当您将数据结构代码(例如 Patient 类(与 I/O 代码(例如扫描仪输入代码(混合在一起时,您的整体程序结构可以得到改进。这些应该是完全独立的,如下所示:

public class TestPatient { 
private int age;
public int getAge(){
return age;
}

public void setAge(int newAge) {
this.age = newAge;
}
}

然后 I/O 可以转到其他地方:

public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// get your data here and create your new TestPatient

}    

为什么这很重要?您事先不知道最终将如何使用主代码,并且需要保持其开放性和灵活性,以便在任何I/O情况下使用,如果需要,包括GUI。

此外,您的代码将为每个 setter 调用创建一个新的 Scanner 对象,这是一件危险的事情,因为如果基于 System.in 的 Scanner 关闭,则程序不再能够从用户那里获取输入。

另请注意,如果不允许传入的数据,则可以从 setter 方法引发异常。

例如,

public void setAge(int newAge) {
if (newAge <= 0) {
String text = "for newAge is less than or equal to 0: " + newAge;
throw new IllegalArgumentException(text);
}
this.age = newAge;
}   

使用while循环。您也不需要newAge参数,因为您正在读取用户输入。

public void setAge(){
int age;
Scanner in = new Scanner(System.in);
boolean success = false;
while (!success) {
try {
System.out.print("Enter in Your age:");
age = in.nextInt();
success = true;
} catch (InputMismatchException ex) {
success = false;
System.out.println("Im sorry, please enter just you age.nTry again");
}
}
this.age=age;
}

最新更新