系统会提示用户输入员工数据的值。我选择扫描整行,然后将每个数据分成一个String数组(用空格分隔)。我创建了变量fullName并连接了员工的名字和姓氏,但是当我打印出代码时,它只显示姓氏。我已经对此进行了三个小时的排查,并且没有发现任何语法或逻辑错误,为什么不打印全名?
\
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Collections;
/**
* Employee Record Class
*
* @Theodore Mazer
* @version 9/8/15
*/
public class EmployeeRecord
{
ArrayList<String> names = new ArrayList<String>();
ArrayList<String> taxIDs = new ArrayList<String>();
ArrayList<Double> wages = new ArrayList<Double>();
private String employeeId = "%03d";
private String taxID;
private double hourlyWage = 0.0;
public ArrayList<String> getNamesArrayList(){ //getter method for employee names
return names;
}
public ArrayList<String> getTaxIdsArrayList(){ //getter method for tax IDs
return taxIDs;
}
public ArrayList<Double> getWagesArrayList(){ //getter method for hourly wages
return wages;
}
public void setEmployeeData(){ //setter method for employee data entry
Scanner scan = new Scanner(System.in);
String firstName = "";
String lastName = "";
String info = "";
System.out.println("Enter each employees full name, tax ID, and hourly wage pressing enter each time. (Enter the $ key to finish)");
while(!(scan.next().equals("$"))){
info = scan.nextLine();
String[] splitString = info.split(" ");
String fullName = "";
firstName = splitString[0];
lastName = splitString[1];
fullName = firstName + " " + lastName;
double hWage = Double.parseDouble(splitString[3]);
names.add(fullName);
taxIDs.add(splitString[2]);
wages.add(hWage);
}
System.out.println("Employee ID | Employee Full Name | Tax ID | Wage ");
for(int i = 0; i <= names.size() - 1; i++){
System.out.printf(String.format(employeeId, i + 1) + " | " + names.get(i) + " | " + taxIDs.get(i) + " | " + wages.get(i));
System.out.println();
}
}
}
答案 0 :(得分:2)
在while
条件下,您使用next()
消耗下一个令牌,在您的情况下,它是第一个名称。
我会对while循环进行两次修改:
while (scan.hasNext()) { // <-- check if there's a next token (without consuming it)
info = scan.nextLine();
if (info.trim().equals("$")){ // <-- break if the user wants to quit
break;
}
String[] splitString = info.split("\\s+"); // split on any amount/kind of space using regex-split
String fullName = "";
firstName = splitString[0];
lastName = splitString[1];
System.out.println(Arrays.toString(splitString));
fullName = firstName + " " + lastName;
double hWage = Double.parseDouble(splitString[3]);
names.add(fullName);
taxIDs.add(splitString[2]);
wages.add(hWage);
}