java - 输出在同一行?

标签 java output

我在输出两个单独的问题时遇到问题。 代码是:

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: ");

...

最佳答案

问题是当你打电话

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();
}

关于java - 输出在同一行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21080404/

相关文章:

java - 使用带有 Samba JCIFS 的 Java 访问文件

java - 如何使用 Super CSV 从 CSV 文件中删除一行?

java - 如何使用mockito在vertx中模拟Handler<AsyncResult<Void>>?

java - JDBC-ORA-00984 : column not allowed here

powershell - Powershell-将控制台输出转换为变量(不是stdout,不是stderr)

c - C中的单链表输出不正确

c++ - 在 C++ 中创建不可更改的报告文件的最佳实践

java - 检查文件结尾未按预期工作

Python strip() 不适用于新行

python - 从 csv 文件中删除特定字符,并重写到新文件