簡體   English   中英

當打印ArrayList乘法值時,它僅顯示->'[]'

[英]While printing ArrayList multipe value it displays only -> '[]'

我在用Java顯示ArrayList的元素時遇到問題。 當返回ArrayList時,它從Views調用到BMIAnalyzier類,該類現在包含偽值表單。 表明
[] []
運行Java文件時。

  1. Views.java

     Switch(choice[0]){ case 1: //Option 1 to display the data fo subject of given subject id. ArrayList<Records> arraylist = analyzier.find(choice[1]); System.out.println(ArrayList); Break; Case 2: //Option 2 to display the data fo subject from the range given of BMI. ArrayList<Records> arraylistList = analyzier.find(Double.parseDouble(choice[1]),Double.parseDouble(choice[2])); for (int i = 0; i < arraylistList.size(); i++){ System.out.println((arraylistList.get(i)).toString()); } Break; default: System.out.println("wrong input"); } 
  2. BMIAnalyzier.java

     public class BMIAnalyzier { public Records find(String sid) { System.out.println(new Records(sid, 0.0, 0.0, 0.0, "none")); return new Records(sid, 0.0, 0.0, 0.0, "none"); } public ArrayList<Records> find(double bmi1, double bmi2) { ArrayList<Records> alr = new ArrayList<>(); alr.add(new Records("S01", 0.0, 0.0, 0.0, "none")); alr.add(new Records("S02", 0.0, 0.0, 0.0, "none")); return alr; } } 
  3. Records.java

     public class Records extends ArrayList<Records> { private String SubjectId; private Double height; private Double width; private Double bmianalyzier; private String categories; public ArrayList <Records> list =new ArrayList<>(); public Records(String sid, Double h, Double w, Double bmi, String c) { } //getter ans setter methods. } 

輸出:

在這里,我輸入選項2和范圍0 100,結果在下面的圖片中,但是我要顯示ArrayList.in中的值以查看我的結果,請單擊this。

主要的奧秘在於您具有Records類擴展ArrayList 我不知道為什么要這樣做,但是在這種情況下,您繼承了ArrayListtoString()方法,因為該方法為空,所以它是呈現[]方法。 您需要為Records類實現toString()

String toString() {
    return subjectId + " " + height + " " + width + " " + bmianalyzier + " " + categories;
}

我想您是Java新手。 您需要首先了解基礎知識。 例如,在您的情況下,ArrayList是一個集合,您可以使用它保存相同類型的多個值。 通過您的Records類,您可以擴展此處不需要的集合。

公共類Records擴展ArrayList <Records> {

應該

公共課記錄{

另外,您應始終向類構造方法提供內容,否則將不會為該對象設置任何值。

    public Records(String sid, Double h, Double w, Double bmi, String c) {
        this.SubjectId = sid;
       // set other values as well
    }

並且,find(String sid)返回Records對象

ArrayList < Records > arraylist = analyzier.find(choice[1]);

應該更改為

Records record = analyzier.find(choice[1]);

要打印Records對象的值,請按照@Niklas的建議進行操作

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM