我正在尝试验证输入表单中的德国邮政编码。 但不知何故,我卡在了第 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;
}
}
}
最佳答案
您是否忘记了 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
}
}
关于java - 验证用户输入时无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40450894/