2015-09-22 65 views
0

用户会被逐行提示输入员工数据的值。我选择扫描整行,然后将每段数据分隔成一个String数组(用空格分隔)。我创建了变量fullName并连接了员工的名字和姓氏,但是当我打印出代码时,它只显示姓氏。我一直在解决这个问题三个小时,并没有发现任何语法或逻辑错误,为什么不打印全名?在Java中打印出串联字符串的问题

\

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

Java是一种面向对象的语言。不要使用并行数组/列表来存储单个对象的属性。用你的领域定义一个类(你的案例中的3个领域),然后有一个这些对象的单一列表。 – Andreas

回答

2

在你使用next()消耗下一个记号,在你的情况下,它的名字的while条件。

我会做出两处修改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); 
} 
+1

它适用于从“”到“\\ s +”的更改,并且我也同意添加.trim语句比我之前的语句更加可靠。非常感激! –