2015-09-22 119 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語句比我之前的語句更加可靠。非常感激! –