简体   繁体   English

For循环不适用于ArrayList

[英]For loop isn't working for ArrayList

Ok basically I am sort of new to ArrayList and i have to use it to make a program of getting some patients ID and then displaying it on the screen using objects and for loop. 好的,基本上我是ArrayList的新手,我必须使用它来制作一个获取患者ID的程序,然后使用对象和for循环将其显示在屏幕上。 I did make the program but my loops aren't executing. 我确实制作了程序,但循环未执行。 this is my program: 这是我的程序:

import java.util.*;
import java.util.ArrayList;
import java.util.Scanner;

public class patient$ {
    public static void main(String[] args) {
        ArrayList<patientss> patient1 = new ArrayList<patientss>();
        Scanner src = new Scanner(System.in);
        int id, i, num;
        String name;
        int ages;
        System.out.println(" j");
        for (i = 0; i < patient1.size(); i++) {
            patientss xx = new patientss();
            System.out.println("Enter the patient's ID ");
            id = src.nextInt();
            xx.setId(id);
            patient1.add(xx);
        }
        patientss tt = new patientss();
        for (i = 0; i < patient1.size(); i++) {
            tt = patient1.get(i);
            System.out.println(tt.getId());
        }
    }
}

and this is my patientss class: 这是我的patientss课:

package samplee.java;
public class patientss {
    int id;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }
}

您的循环在一个空的ArrayList上运行,因此size()方法将返回0。尝试将第一个for循环中的size()方法更改为要添加的许多patientss

Your first loop is iterating over an empty ArrayList. 您的第一个循环是遍历一个空的ArrayList。

Since the point of this loop seems to be to be adding things to that list, the number of iterations should be controlled by how many things you want to add to it, not how many are already in it. 由于此循环的重点似乎是要向列表中添加东西,因此迭代次数应由要添加到其中的东西(而不是已经包含多少东西)控制。 For example, the loop could continue as long as patient1.size()<N , where N is the number of items you want to add. 例如,只要patient1.size()<N ,循环就可以继续,其中N是您要添加的项目数。

Here's one solution. 这是一个解决方案。 Replace the first loop with my code. 用我的代码替换第一个循环。

Boolean leave = false;
while (!leave) {
    patientss xx = new patientss();
    System.out.println("Enter the patient's ID ");
    System.out.println("-1 to finish entering");
    id = src.nextInt();
    if (id != -1) {
        xx.setId(id);
        patient1.add(xx);
    } else { leave = true; } //Escape the while loop.
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM