gpt4 book ai didi

Java toString 与 2 个数组列表

转载 作者:行者123 更新时间:2023-12-01 17:43:07 25 4
gpt4 key购买 nike

所以基本上我有一个 Invoice 类,它有 2 个数组。一个用于项目列表,一个用于价格列表。我希望我的 toString 函数在调用时打印商品的名称,左对齐,正好有 15 个字符,然后是它的价格,有 6 个字符和小数点后 2 位。但是,我不确定我的代码有什么问题:

import java.util.*;
public class Invoice {
private String name;
private ArrayList<String> items;
private ArrayList<Double> prices;

public Invoice(String _name) {
name = _name;
items = new ArrayList<String>();
prices = new ArrayList<Double>();
}

public int getCount() {
return items.size();
}
public String getName() {
return name;
}

public void addItem(String item, double price) {
items.add(item);
prices.add(price);
}

public double getTotal() {
double total = 0.0;
for(double pr : prices) {
total += pr;
}
return total;
}

public String toString() {
String r = "";
r += "Invoice for ";
r += name;
r += "\n";
for(String item : items) {
r += "\n";
r += String.format("%-15.15s", item);
}
for(double price: prices) {
r += String.format("%6.2f", price);
}
return String.format(r);
}

}

当我在测试类中输入输入时,我希望输出为

Toaster         15.95
Smart Phone 327.63

但是,我的输出是:

Toaster
Smart Phone 15.95327.63

感谢任何可以帮助我解释这一点的人

最佳答案

在我看来,您首先打印所有商品( toastr 和智能手机),然后打印所有价格,在这里:

for(String item : items) {
r += "\n";
r += String.format("%-15.15s", item);
}
for(double price: prices) {
r += String.format("%6.2f", price);
}

你真正想做的是打印第一个项目,第一个价格,第二个项目,第二个价格等。所以像这样:

for(int i = 0; i < items.length; i++) {
// Handle item
r += "\n";
r += String.format("%-15.15s", items[i]);

// Handle price
r += String.format("%6.2f", prices[i]);

}

关于Java toString 与 2 个数组列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58596673/

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