簡體   English   中英

在Java中打印出串聯字符串時出現問題

[英]Problems Printing out a Concatenated String in Java

提示用戶逐行輸入員工數據。 我選擇掃描整行,然后將每條數據分成一個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();
        }
}

}

while條件中,您正在使用next() ,它使用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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM