验证用户输入时无限循环

时间:2016-11-06 15:12:26

标签: 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;
        }
    }
}

1 个答案:

答案 0 :(得分: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
    }
}