有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java在打印ArrayList multipe值时,仅显示>'[]'

我在Java中显示ArrayList的元素时遇到问题。当从视图调用它时返回ArrayList时,返回现在包含伪值表单的bmiAnalyzer类。它显示
[] []
当java文件运行时

  1. 观点。爪哇

    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. BMI分析仪。爪哇

    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. 记录。爪哇

    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.
    }
    

输出:

here I enter the option 2 and range 0 100 and result is in the picture below but that what I wanted to display the values which are in the ArrayList.to see the result of mine click this .


共 (2) 个答案

  1. # 1 楼答案

    我想你是java新手吧。你需要先了解基本知识。例如,在您的示例中,ArrayList是一个用于保存相同类型的多个值的集合。使用Records类,您可以扩展此处不需要的集合

    public class Records extends ArrayList < Records > {

    应该是

    public class Records {

    此外,您应该始终向类构造函数提供内容,否则不会为对象设置任何值

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

    并且,find(stringsid)返回记录对象

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

    应改为

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

    要打印记录对象的值,请按照@Niklas的建议执行

  2. # 2 楼答案

    主要的奥秘在于Records类扩展了ArrayList。我不知道您为什么要这样做,但是在这样的情况下,您继承了ArrayListtoString()方法,这是呈现[]的方法,因为数组是空的。您需要为Records类实现toString()

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