我正在做一個練習,我在陣列中存盤物件,問題是當我要列印陣列中的物件時,顯示的是String型別的值,輸出結果是:
AFGH
AFGH
3
5 5
2 2
3 3
5 5
5 5
1
2 2
5 5
7 7
我的代碼是:
public static void main(String[] args){
Bill[] billsList = new Bill[5] 。
Scanner scanner = new Scanner(System.in)。
String productCode = " "/span>;
int kilos = 0;
int price = 0;
for(int i = 0; i < billsList.length; i ) {
System.out.println("Digit the code of the product: ")。
productCode = scanner.nextLine();
scanner.nextLine();
System.out.println("輸入售出的公斤數:")。
kilos = scanner.nextInt();
System.out.println("Digit the price: ");
價格= scanner.nextInt();
Bill bills = new Bill(productCode,kilos,price)。
billsList[i] = bills。
}
for(int i = 0; i < billsList.length; i ) {
System.out.println(billsList[i])。
System.out.println(billsList[i])。
System.out.println(billsList[i])。
}
}
類Bill的代碼是這樣的:
public class Bill {
private String productCode;
private int kilosSold;
private int price;
public Bill(String productCode,int kilosSold,int price) {
this.productCode = productCode。
this.kilosSold = kilosSold;
this.price = price;
}
uj5u.com熱心網友回復:
在Bill類中,你必須覆寫Object類的toString()方法。
有點像:
@Override
public String toString() {
return "Product : " productCode " kilosold : " kilosSold "price : " 價格。
}
或者你可以選擇使用lombok的@ToString來避免這種模板代碼。
另外,你可以把你的類的資料成員改為final。
有點像:
private final String productCode。
private final int kilosSold;
private final int price;
uj5u.com熱心網友回復:
去掉nextLine,它就可以正常列印了:
System.out.println("Digit the code of the product: ")。
productCode = scanner.next();
System.out.println("輸入售出的公斤數:")。
kilos = scanner.nextInt();
此外,你應該像上面回答的那樣覆寫toString方法。
uj5u.com熱心網友回復:
如果你想列印一個完整的物件陣列,以及所有的屬性,你應該使用Arrays類方法 "toString"。如果你只想要其中一個屬性,例如:產品代碼,你應該使用getter方法。調查一下getter和setter方法,它將對你有很大的幫助。
public static void main(String[] args){
Bill[] billsList = new Bill[5] 。
Scanner scanner = new Scanner(System.in)。
String productCode = " "/span>;
int kilos = 0;
int price = 0;
for(int i = 0; i < billsList.length; i ) {
System.out.println("Digit the code of the product: ")。
productCode = scanner.nextLine();
System.out.println("輸入售出的公斤數:")。
kilos = scanner.nextInt();
System.out.println("Digit the price: ");
價格= scanner.nextInt();
Bill bills = new Bill(productCode,kilos,price)。
billsList[i] = bills。
}
System.out.println(Arrays.toString(billsList))。
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/332977.html
標籤:
