我在输出两个单独的问题时遇到问题。 代码是:
System.out.println("Please enter full name: ");
String name = keyboard.nextLine();
while (name.length() >= 21)
{
System.out.println("Name is invalid, please re enter:");
name = keyboard.nextLine();
}
System.out.println("Please enter reference number: ");
String reference = keyboard.nextLine();
while (reference.length() > 6) {
System.out.println("Refrence incorrect, please re enter");
reference = keyboard.nextLine();
}
while (!reference.matches("(?i)[A-Z]{2}[0-9]{3}[A-Z]")) {
System.out.println("Reference is incorrect, please re-enter:");
reference = keyboard.nextLine();
然而输出的内容类似于:
Please enter full name:
Please enter reference number:
没有空间让我输入名称或参考。即使我这样做,也要求再次参考。有人能在我的代码中发现任何问题吗? (如果你不能告诉我优雅的编码哈哈,我是初学者)
之前的代码是:
Scanner keyboard = new Scanner(System.in);
System.out.println("Please select from the following options:");
System.out.println("1. Enter new Policy");
System.out.println("2. Display summary of policies");
System.out.println("3. Display summary of policies for selected month");
System.out.println("4. Find and display Policy");
System.out.println("0. Exit");
int option = keyboard.nextInt();
if (option == 1) {
System.out.println("Please enter full name: ");
...
答案 0 :(得分:1)
问题在于你打电话
int option = keyboard.nextInt();
它不会读取最后一个换行符,您可以通过调用
来解决此问题int option = Integer.parseInt(keyboard.nextLine());
nextLine()
也会使用换行符,但会返回String
,因此您需要将其解析为Integer
。
修改强>
如果输入(在nextInter
中)不是整数,则会得到NumberFormatException
。要处理此问题,您必须使用try-catch
子句:
int option;
try {
option = Integer.parseInt(keyboard.nextLine());
} catch (NumberFormatException e) {
e.printStackTrace();
}