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