我觉得我几乎有这个权利。错误表明(!isinputValid(未初始化。试图弄清楚为什么会这样,以及如何改变它,这样我的问题就会重复出现无效输入(超过24个(。
boolean isInputValid;
// The license plate must be a string and imported using next(), max 24hr parking
for (int i = 0; i < licensePlates.length; i++) {
System.out.println("Auto" + (i + 1));
System.out.print(" Kenteken: ");
licensePlates[i] = input.next();
System.out.print(" Geparkeerde uren (max. 24): ");
parkingTime[i] = input.nextInt();
if (parkingTime[i] > 24){ // the max time for parking is 24hr
isInputValid = false;
System.out.println(" De parkeerduur kan maximaal 24 uur zijn");
}
while (!isInputValid);
}
}
}
按如下操作:
do {
isInputValid = true;
System.out.print(" Geparkeerde uren (max. 24): ");
try {
parkingTime[i] = Integer.parseInt(input.nextLine());
if (parkingTime[i] > 24) { // the max time for parking is 24hr
isInputValid = false;
System.out.println(" De parkeerduur kan maximaal 24 uur zijn");
}
} catch (NumberFormatException e) {
isInputValid = false;
}
} while (!isInputValid);
另外,请注意,我使用了nextLine()
而不是nextInt()
。检查扫描仪在使用next((或nextFo((后是否跳过nextLine((?了解更多信息。