简体   繁体   中英

How to store an “infinite” number of integers in an ArrayList (Java)

So I have a method that takes in numbers the user would like to input and stores them into an Array List. Right now I have the following method:

public static ArrayList<Integer> inputArrayList(){

    ArrayList<Integer> a = new ArrayList<Integer>();
    Scanner scan = new Scanner(System.in);

    int t;
    for(int i=0;i<10000;i++){
        t = scan.nextInt();
        if(t!=0){
            a.add(t);                                                                                              
        }else{
            i+=200000;
        }
    }
    return a;
}

I would like to improve it so that the method could technically take in an infinite number of values (not 10,000) because I feel like right now that while it would logically not be likely someone would put more values in than 10,000, I still feel the code as of now is sloppy.

I also would like to be able to enter any number and have it be stored in the ArrayList as well, including the number 0 which currently acts as a sort of sentinel value. However, I can't think of another way to do so.

Any help is greatly appreciated.

ArrayList takes an index of type int , so you can only index up to the max value of an integer.

You can handle a stream of values, but it won't be using an ArrayList . You should rethink your requirement and implementation.

You can change your condition to exit when you get a zero.

boolean accumulating = true;
while(accumulating){

    accumulating = scan.hasNextInt();
    if(accumulating){
        a.add(scan.nextInt());                                                                                              
    }

}

This will exit if the user enters something that is not an int. There is a litmitation because you are using an ArrayList ,and you can only hold Integer.MAX_VALUE elements.

Or more concisely.

while(scan.hasNextInt()){
   a.add(scan.nextInt());
}
int t = 0;
int u = 1;
while(u != 0){
    t = scan.nextInt();
    a.add(t);
    u = scan.nextInt();                                                                                              
}

This is the simplest implementation I can think of right now. Pretty straight forward, just use another variable to keep track of whether to exit the loop, add to infinity otherwise. Now it accepts any integer up to the innate limit.

I think you need to make something like this :

System.out.println("If you want to exit, enter any non number?");
int t;
do {
    try {
        t = scan.nextInt();
        a.add(t);
    } catch (NumberFormatException e) {
        break;//if the user enter a non number break your loop
    }

} while (true);//loop until the user enter a non number

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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