Rajdeep Sahoo
Rajdeep Sahoo

Reputation: 77

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.

Upvotes: 0

Views: 68

Answers (3)

meskobalazs
meskobalazs

Reputation: 16031

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.

Upvotes: 2

Harshit
Harshit

Reputation: 5157

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"));

Upvotes: 0

Amila
Amila

Reputation: 5213

You can use java.util.List

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

Upvotes: 0

Related Questions