2

I'm trying to validate german postcodes in a input form. But somehow i get stuck in line 15 and my function is just printing "Give me input" in an endless loop.

I expected that sc_plz.nextLine() would be a blocking function but somehow it's not.

import View.AddressView;

import java.io.IOException;
import java.util.Scanner;

public class AddressController {
    AddressView view = new AddressView();

    public Address addAddress()throws IOException{
        //other input questions

        Scanner sc_plz = new Scanner(System.in);
        int code = 0;
        while (!validatePostcode(code))
            view.askPostcode(); //simple System.out.println("Input something")
            String postcode = sc_plz.nextLine();

            try {
                code = Integer.parseInt(postcode);
            }
            catch (NumberFormatException e){
                view.invalidData(); //warning about not got a number
            }
        //other input questions
    }

    private boolean validatePostcode(int plz) throws IOException {
        //legal postcodenumbers are between 01000 -99999
        if (1000 <= plz && plz <= 99999){
            return true;
        }
        else {
            return false;
        }
    }
}
1
  • Where is "Give me input" being printed? Is it done by view.askPostcode();? Commented Nov 6, 2016 at 15:20

1 Answer 1

7

Did you forget brackets for your while statement? As it is right now it will always do whatever is in view.askPostcode();. I imagine this is what it should look like:

while (!validatePostcode(code)) {
    view.askPostcode(); //simple System.out.println("Input something")
    String postcode = sc_plz.nextLine();
    try {
        code = Integer.parseInt(postcode);
    } catch (NumberFormatException e){
        view.invalidData(); //warning about not got a number
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

ugh... yes. staring at it for hours but beeing blind for this. thx!
@DennyCrane configuring your editor to auto-indent your code makes such mistakes a lot more obvious.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.