[英]How to combine a one-dimensional array with a two-dimensional array
我有一系列客戶姓名:
String[] customers = {"Joe Dirt", "John Dirt", "Josh Dirt"};
我還有一個包含賬戶號碼/付款的二維數組:
double[][] payments = {{1011,12,54,39},{1012,55,65,48},{1013,56,92,55}};
我需要將客戶的姓名與他們的帳戶和付款進行匹配並打印出來。 arrays 已經排序,我只需要打印出“Joe Dirt 1011、12、54、55”等等。我試圖了解如何循環遍歷二維數組。
這就是我所擁有的:
public static ArrayList<String> combineArray(String[] customers,
double[][] payments) {
ArrayList<String> customerPayments = new ArrayList<String>();
String result = "";
String custName = "";
String acctInfo = "";
for (String n : customers) {
custName = n;
for (double[] x : payments) {
for (double y : x) {
acctInfo = String.valueOf(y);
}
}
result = custName + acctInfo;
customerPayments.add(result);
}
return customerPayments;
}
它正確打印出客戶姓名,但僅打印出付款二維數組的最后一個值。 前任。
Joe Dirt55
John Dirt55
Josh Dirt55
我在這里俯瞰什么?
例如,您可以這樣做:
String[] customers = {"Joe Dirt", "John Dirt", "Josh Dirt"};
double[][] payments = {{1011,12,54,39},{1012,55,65,48},{1013,56,92,55}};
for (int i = 0; i < customers.length; i ++) {
System.out.println(customers[i] + Arrays.toString(payments[i]));
}
或者,如果您想查看不帶括號的 output 字符串,請嘗試這樣做:
for (int i = 0; i < customers.length; i++) {
System.out.println(customers[i] + " " +
Arrays.toString(payments[i]).replaceAll("\\[|\\]", ""));
}
您可以采取多種方法。 首先,我建議你編程到List
接口(而不是ArrayList
具體類型)。 其次,在第一個數組中使用顯式索引,以便您可以在payments
數組中跟蹤您的 position。 第三, StringJoiner
可能對組合元素很有用。 就像是,
public static List<String> combineArray(String[] customers, double[][] payments) {
List<String> customerPayments = new ArrayList<>();
for (int i = 0; i < customers.length; i++) {
StringJoiner sj = new StringJoiner(", ");
for (double x : payments[i]) {
sj.add(String.format("%.0f", x));
}
customerPayments.add(String.format("%s %s", customers[i], sj));
}
return customerPayments;
}
為了更容易驗證
public static void main(String[] args) {
String[] customers = { "Joe Dirt", "John Dirt", "Josh Dirt" };
double[][] payments = {
{ 1011, 12, 54, 39 },
{ 1012, 55, 65, 48 },
{ 1013, 56, 92, 55 }
};
combineArray(customers, payments).stream().forEach(System.out::println);
}
我得到
Joe Dirt 1011, 12, 54, 39
John Dirt 1012, 55, 65, 48
Josh Dirt 1013, 56, 92, 55
customers
周期中使用索引,以便您可以使用它來獲得相應的payments
acctInfo
,而不是每次都替換它的值customers
周期開始時清除acctInfo
,這樣它就不會累積以前客戶的付款例如:
public static ArrayList<String> combineArray(String[] customers, double[][] payments) {
ArrayList<String> customerPayments = new ArrayList<>();
for (int i = 0; i < customers.length; i++) {
String acctInfo = "";
String custName = customers[i];
for (double y : payments[i]) {
acctInfo += String.valueOf(y);
}
String result = custName + acctInfo;
customerPayments.add(result);
}
return customerPayments;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.