gpt4 book ai didi

java - 在 Java 中打印连接字符串时出现问题

转载 作者:行者123 更新时间:2023-12-02 04:21:39 26 4
gpt4 key购买 nike

系统会提示用户逐行输入员工数据的值。我选择扫描整行,然后将每条数据分成一个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() 来消耗下一个标记,在您的情况下,它是第一个名称。

我将对 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);
}

关于java - 在 Java 中打印连接字符串时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32707598/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com