验证用户输入时无限循环

Den*_*ane 2 java

我正在尝试以输入形式验证德语邮政编码.但不知何故,我陷入第15行,我的功能只是在无限循环中打印"给我输入".

我期望sc_plz.nextLine()将是一个阻塞函数,但不知何故它不是.

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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Mat*_*ght 7

您是否忘记了while语句的括号?就像现在一样,它总会做任何事情view.askPostcode();.我想这应该是这样的:

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
    }
}
Run Code Online (Sandbox Code Playgroud)