Denny Crane Denny Crane - 1 month ago 8
Java Question

Endless loop while validating user input

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;
}
}
}

Answer

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
    }
}