Java程序无法正确执行nextLine()函数

3
当我运行程序时,它没有读取字符串并将其存储在tempAddress中,而是在我输入之前直接打印下一行。对于前两个单词,使用next可以工作,但第三个单词包含多个单词,因此需要其他方法。通过我的研究,我发现nextLine()是答案,但我无法像其他人那样使其正常工作,提前感谢您的帮助。
System.out.println("Enter Employee First Name: ");
String tempFirstName = input.next();
employeesArray[i].setFirstName(tempFirstName);

System.out.println("Enter Employee Last Name: ");
String tempLastName = input.next();
employeesArray[i].setLastName(tempLastName);

System.out.println("Enter Employee Address: ");
String tempAddress = input.nextLine();
employeesArray[i].setAddress(tempAddress);

System.out.println("Enter Employee Title: ");
String tempTitle = input.next();
employeesArray[i].setTitle(tempTitle);

你对nextLine()有什么期望?为什么你觉得“无法使其正常工作”? - Balwinder Singh
期望从用户读取输入... 如上所述,"我的程序在我输入之前只是简单地打印下一行"。 - hoss24
这段代码对我有效:System.out.println("输入员工地址:"); String tempAddress = input.nextLine(); System.out.println("tempAddress : " + tempAddress); - Balwinder Singh
它将解释为什么以及如何无法正常工作。该方法正在执行其工作。 - Balwinder Singh
2个回答

2
基本上,Scanner默认使用空格分词输入。使用Scanner的next()方法返回第一个token,指针停留在这里。使用nextLine()返回整行,然后将指针移动到下一行。
之前您使用next()输入员工姓氏导致指针停留在该行中,因此当您到达使用nextLine()输入员工地址的时候,指针会返回先前使用next()输入的剩余部分,该输入显然为空(当向next()输入一个单词时)。假设您输入了由空格分隔的两个单词作为姓氏,next()将把第一个单词存储在姓氏字段中,并将指针等待在第二个标记之前,当您到达nextLine()时,指针将返回第二个标记并移动到新行。
解决方案是在读取姓氏输入后执行nextLine(),以确保指针位于等待地址输入的新行中。
我通过在那里插入input.nextLine()来更新我的代码,以确保扫描输入被消费并且指针移动到下一行。
    System.out.println("Enter Employee First Name: ");
    String tempFirstName = input.next();
    employeesArray[i].setFirstName(tempFirstName);

    System.out.println("Enter Employee Last Name: ");
    String tempLastName = input.next();
    employeesArray[i].setLastName(tempLastName);

    //feed this to move the scanner to next line
    input.nextLine(); 

    System.out.println("Enter Employee Address: ");
    String tempAddress = input.nextLine();
    employeesArray[i].setAddress(tempAddress);

    System.out.println("Enter Employee Title: ");
    String tempTitle = input.next();
    employeesArray[i].setTitle(tempTitle);

请添加一些解释。 - tungd
1
这个可以工作,但是如果你不想在输入中有空格,该怎么办呢?那你就得为此单独创建一个东西。 - 789
我已更新答案,并且更新了代码,修复了他的问题。@789和tungd感谢指出问题。 - Raf
@789 是的,只要姓氏始终是一个标记 - 这是自然的。nextLine() 会将其移动到新行,无论如何。 - Raf
@user2383106 很高兴能帮到你。如果这个问题对你有用并且你从我的回答中学到了东西,请点赞;) - Raf

1
当您使用时,它会读取输入,但不包括字符,它将保留在输入流中。 以字符结束。因此,当执行时,它会停止而不采取任何输入,因为它已经从输入流获取了(\ n)字符。
解决方案:在执行之前读取。
System.out.println("Enter Employee Address: ");
input.next();//read the newline char - and don't store it, we don't need it.
String tempAddress = input.nextLine();

参见:https://dev59.com/cmcs5IYBdhLWcg3wJQi7#13102066


谢谢你的帮助,我已经接受了其他答案,因为它是第一个,但一定会给你的答案和评论点赞。 - hoss24

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接