How can I capture a system.err and display a message to the user rather than have the terminal window appear?
The class that contains the line is NOT allowed to be modified. Heres the code:
Entry Class:
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 Class:
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";
}
Extended entry class:
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;
}
Current call to add entry from the GUI class:
entry = Personal(firstName, lastName, street, town, postcode.toUpperCase(), dob);
message = addressbook.add(entry);
If I enter a bad postcode at present I get the terminal window stating "Bad poscode: " it then creates an entry with ??? as the postcode. I want to be able to alert the user asking for another input without adding the entry. I dont know how to do this however without changing the Entry class (not allowed to modify either the Entry or AddressBook classes).
You can use
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();
}
prints
ERR Hello World ERR
ERR java.lang.Throwable: HERE ERR
ERR at Main.main(Main.java:24) ERR
Why not do all the validation checks at Personal
class itself when you are creating that object in first place? Make sure the only those objects having valid data are created. Solves your issue.
I would say do those checks and show him all errors in your person class itself.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.