I dont know why the output will repeat multiple times, and I dont know how to format output.

I want to extract the last four digit from a string, and treat it as a post code.

This code will receive user input, check if the last four characters are digit.

If it is, extract it, and show it on the screen.
If it is not, return error.

Now, I think I can extract it, but I don’t know how to display it with format(I cannot simply overwrite toString() method because many other parts in my project need formatting display, while each uses different format.)

Plus, why the code generates multiple outputs, rather than one?

Here is the code:

    public static void main(String[] args) {
    String address;
    Scanner scn = new Scanner(System.in); 
    address = scn.next();
    String postcode = "1234";
    //this part extract postcode for further process.
    for(int count=1;count<5;count++)
            String[] split = postcode.split(address); 
            System.out.format("%s %s %n", "PO is: ", split);
            System.out.println("PO invalid!");

One possible output is this:


PO is: [Ljava.lang.String;@a46701

PO is: [Ljava.lang.String;@166a22b

PO is: [Ljava.lang.String;@120cc56

PO is: [Ljava.lang.String;@47393f

Output will display once if I have 1 digit in the end. Will display twice if I have 2 digits. Output will display up to 4 times if I have 4 or more digits in the end.

I realize there must be something wrong in if section, but I don’t know why.

Thanks for the patience.

Source: regex

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.