如何捕获system.err并向用户显示消息而不是显示终端窗口?
不允许修改包含该行的类。下面是代码:
入门级:
public Entry(String paramString1, String paramString2, String paramString3, String paramString4, String paramString5)
{
this.firstName = paramString1;
this.lastName = paramString2;
this.street = paramString3;
this.town = paramString4;
if (paramString5.matches("[A-Z]{2}[0-9]{1,2} [0-9]{1,2}[A-Z]{2}")) {
this.postCode = paramString5;
} else {
System.err.printf("Bad postcode: '%s'\n", new Object[] { paramString5 });
this.postCode = "???";
}
}
AddressBook类:
public String add(Entry paramEntry)
{
if (paramEntry == null)
return "Error: null entry";
if (this.data.contains(paramEntry)) {
return "Error: this entry already in the book";
}
boolean bool = this.data.add(paramEntry);
if (bool) {
return " entry added";
}
return "entry could not be added";
}
扩展入门级:
public class Personal extends Entry
{
private String dob;
public Personal(String firstName, String lastName, String street, String town, String postcode, String theDOB)
{
super(firstName, lastName, street, town, postcode);
dob = theDOB;
}
当前调用以从GUI类添加条目:
entry = Personal(firstName, lastName, street, town, postcode.toUpperCase(), dob);
message = addressbook.add(entry);
如果我目前输入一个糟糕的邮政编码,我会在终端窗口显示“Bad poscode:”然后它会创建一个带有???的条目作为邮政编码。我希望能够在不添加条目的情况下提醒用户询问其他输入。我不知道怎么做但不改变Entry类(不允许修改Entry或AddressBook类)。
答案 0 :(得分:2)
您可以使用
public static void main(String... ignored) {
System.setErr(new PrintStream(new OutputStream() {
private StringBuilder line = new StringBuilder();
@Override
public void write(int b) throws IOException {
if (b == '\n') {
String s = line.toString();
line.setLength(0);
// TODO fill in what you want to do
System.out.println("ERR " + s + " ERR");
} else if (b != '\r') {
line.append((char) b);
}
}
}));
System.err.println("Hello World");
new Throwable("HERE").printStackTrace();
}
打印
ERR Hello World ERR
ERR java.lang.Throwable: HERE ERR
ERR at Main.main(Main.java:24) ERR
答案 1 :(得分:0)
为什么不首先在Personal
类中进行所有验证检查?确保仅创建具有有效数据的对象。解决您的问题。
我会说那些检查并向他显示你班级本身的所有错误。