Java: how do I initialize an array size if it's unknown?

前端 未结 7 636
庸人自扰
庸人自扰 2021-02-04 03:47

I\'m asking the user to enter some numbers between 1 and 100 and assign them into an array. The array size is not initialized since it is dependent on the number of times the us

相关标签:
7条回答
  • 2021-02-04 04:19

    I agree that a data structure like a List is the best way to go:

    List<Integer> values = new ArrayList<Integer>();
    Scanner in = new Scanner(System.in);
    int value;
    int numValues = 0;
    do {
        value = in.nextInt();
        values.add(value);
    } while (value >= 1) && (value <= 100);
    

    Or you can just allocate an array of a max size and load values into it:

    int maxValues = 100;
    int [] values = new int[maxValues];
    Scanner in = new Scanner(System.in);
    int value;
    int numValues = 0;
    do {
        value = in.nextInt();
        values[numValues++] = value;
    } while (value >= 1) && (value <= 100) && (numValues < maxValues);
    
    0 讨论(0)
提交回复
热议问题