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();
    address=address.trim();
    String postcode = "1234";
    //this part extract postcode for further process.
    for(int count=1;count<5;count++)
    {
        if(Character.isDigit(address.toCharArray()[address.length()-count]))
        {
            String[] split = postcode.split(address); 
            System.out.format("%s %s %n", "PO is: ", split);
        }
        else
        {
            System.out.println("PO invalid!");
            System.exit(0);
        }
    }
}

One possible output is this:

qweqwr2132

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