gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:40:45 27 4
gpt4 key购买 nike

当我运行我的程序而不是读取字符串并将其存储在 tempAddress 中时,我的程序只是在我输入之前打印下一行。对前两个使用下一个作品,因为我只使用一个词,但第三个词包含多个词,所以需要其他东西,通过我的研究,我发现 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);

最佳答案

基本上,Scanner 默认使用空格对输入进行分词。使用扫描仪的 next() 方法返回空格之前的第一个标记,指针停留在那里。使用 nextLine() 返回整行,然后将指针移动到下一行。

您的 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);

关于Java 程序无法正确执行 nextLine(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33793747/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com