简体   繁体   中英

How to take a large no of inputs where no of input is unknown?

import java.util.*;
public class cv {
    public static void main(String[] args) {
        Scanner input = new Scanner(System. in );
        int[] itemprice;
        itemprice = new int[100000];
    }
}

Here I want to take a large no of inputs but the no of inputs are not known to me.

You can use a list to store the items. The collection will resize the backing data structure (in this example an array) if it is neccessary.

public static void main(String[] args) {
    List<Integer> itemPrices = new ArrayList<>();
    try (Scanner input = new Scanner(System.in)) {
        String text;
        while (true) {
            System.out.print("Do you want to enter another value? ");
            text = input.nextLine();
            if (!text.trim().toLowerCase().equals("yes")) {
                break;
            } else {
                System.out.print("Next value: ");
                itemPrices.add(input.nextInt());
            }
        }
    }
}

This reads integers into the itemPrices list, as long as you answer yes to the question.

Use this

String ans = "Yes";
do {
    Scanner input = new Scanner(System. in );
    int[] itemprice;
    itemprice = new int[100000];
    System.out.print("Do you want to enter another value?");
    ans = input.nextLine();
} while (ans.toLowerCase().equals("Yes"));

您可以使用java.util.List

List<Integer> itemPrice = new ArrayList<>();

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