Pcl*_*lef 1 java exception-handling exception try-catch java.util.scanner
有没有办法压缩try/catch块代码?现在,我的代码在try/catch代码中有一个try/catch代码.
if(petType.equals("DOG")) {
try {
String name = input.next();
String owner = input.next();
double weight = input.nextDouble();
SimpleDateFormat stdDate = new SimpleDateFormat("MM/dd/yy");
try {
Date vaccineDate = stdDate.parse(input.next());
boolean fixed = input.nextBoolean();
Dog x = new Dog(name,owner,weight,vaccineDate,fixed);
object.addPet(x);
}
catch (ParseException ex) {
System.out.println("ERROR - Vaccine date " + input.next() + " is not in mm/dd/yy format!");
input.nextLine();
}
}
catch(NoSuchElementException ex) {
System.out.println("ERROR - Missing fields. Skipping line " + lineNumber + "...");
input.nextLine();
}
}
Run Code Online (Sandbox Code Playgroud)
你可以做到这一点
if(petType.equals("DOG")) {
try {
String name = input.next();
String owner = input.next();
double weight = input.nextDouble();
SimpleDateFormat stdDate = new SimpleDateFormat("MM/dd/yy");
Date vaccineDate = stdDate.parse(input.next());
boolean fixed = input.nextBoolean();
Dog x = new Dog(name,owner,weight,vaccineDate,fixed);
object.addPet(x);
}
catch(NoSuchElementException ex) {
System.out.println("ERROR - Missing fields. Skipping line " + lineNumber + "...");
input.nextLine();
}
catch (ParseException ex) {
System.out.println("ERROR - Vaccine date " + input.next() + " is not in mm/dd/yy format!");
input.nextLine();
}
}
Run Code Online (Sandbox Code Playgroud)
或者使用Java 7
try {
...
} catch(ParseException | NoSuchElementException ex) {
...
}
Run Code Online (Sandbox Code Playgroud)
如果这就是压缩的意思.
| 归档时间: |
|
| 查看次数: |
519 次 |
| 最近记录: |