[英]Java toString with 2 array Lists
所以基本上我有一个 class,发票,有 2 个 arrays。 一个用于项目列表,一个用于价格列表。 我希望我的 toString function 在调用时打印项目的名称,左对齐,正好有 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);
}
}
当我在测试 class 中输入输入时,我想要 output
Toaster 15.95
Smart Phone 327.63
但是,我的 output 是:
Toaster
Smart Phone 15.95327.63
感谢任何可以帮助向我解释这一点的人
在我看来,您首先打印所有物品(烤面包机和智能手机),然后是所有价格,这里:
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]);
}
正如其中一条评论所述,这是使用 Object 面向编程原理的绝佳机会。 而不是单独的项目和价格列表,您应该有一个代表“项目”的单个 object,它有名称和价格:
public class InvoiceItem {
private String name;
private Double price;
public InvoiceItem(String name, Double price) {
this.name = name;
this.price = price;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
@Override
public String toString() {
return String.format("%-15.15s", name) + String.format("%6.2f\n", price);
}
}
请注意,我重写了toString()
方法,以便每个 InvoiceItem 都知道如何打印自己。
然后,在您的发票 class 中,您可以执行以下操作:
public class Invoice {
private String name;
private List<InvoiceItem> items; // <-- use List instead of ArrayList here
public Invoice(String name) {
this.name = name;
this.items = new ArrayList<>();
}
// I'll leave the implementation of the other methods as an exercise for the reader
public String toString() {
// StringBuilders are great of iteratively constructing Strings
StringBuilder sb = new StringBuilder();
for (InvoiceItem item : items) {
sb.append(item.toString());
}
return sb.toString();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.