java nextline next_Java程序无法正确提取nextLine()

本文讲述了如何修复Java程序在读取员工姓名和地址时遇到的问题,通过理解next()和nextLine()的差异,以及在适当位置调用nextLine()来确保正确接收多词输入。作者建议在读取完姓氏后调用input.nextLine(),以避免指针残留问题。
摘要由CSDN通过智能技术生成

当我运行程序而不是读取字符串并将其存储在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);

解决方法:

基本上,默认情况下,扫描程序会使用空格将输入标记化.使用扫描仪的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

来源: https://codeday.me/bug/20191119/2035990.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值