0

Quick overview of our assignment: User needs to enter grades received. We do not know how many grades user needs to enter. If the user enters "-1" thats when we know the user is done entering grades.

Problem is how do you use a counter and assign values to an array in the same loop? I would rather not have to ask the user to enter all values twice (Once to get array size and the second time to assign grades to index positions).

Our professor gave us a handout that tells us to basically guess the size of the array and hope for the best. I refuse to believe that's the only solution.

Any help would be appreciated. Thanks.

8
  • For your case, it is better to use data structure like LinkedList. Commented Jun 10, 2014 at 4:14
  • @fajarkoe Really just a List/ArrayList :| Commented Jun 10, 2014 at 4:14
  • If you can't use List (for whatever terrible reason - e.g. school assignment xD), consider creating an array larger than number of values that can be entered (memory is pretty darn cheap), and possibly a count of how many values have been entered: this avoids having to deal with resizing (or, creating a new array and copying) or re-iterating the [user] input. Commented Jun 10, 2014 at 4:15
  • @user2864740 If you use LinkedList, you don't have to worry about having to enlarge the backing array as in ArrayList. Commented Jun 10, 2014 at 4:17
  • @fajarkoe If I use an ArrayList, I don't have to worry about the backing array either .. and the performance overhead of the occasional backing array resize is fairly well amortized. A LinkedList also has additional fixed per-element overhead and increased allocation requirements. (That is, except in cases where I know and can/care to show that a LinkedList was a better implementation, where such even matters, I use an ArrayList.) Commented Jun 10, 2014 at 4:18

4 Answers 4

3

You can't make dynamic array in java.

For that you will have to use List or ArrayList.

We will have to provide the size of array before application run or at coding time, while arrayList gives us facility to add data while we need it, so it's size will automatically increased when we add data.

Example :

import java.util.*;

public class ArrayListDemo {
   public static void main(String args[]) {
      // create an array list
      ArrayList al = new ArrayList();
      System.out.println("Initial size of al: " + al.size());

      // add elements to the array list
      al.add("C");
      al.add("A");
      al.add("E");
      al.add("B");
      al.add("D");
      al.add("F");
      al.add(1, "A2");
      System.out.println("Size of al after additions: " + al.size());

      // display the array list
      System.out.println("Contents of al: " + al);
      // Remove elements from the array list
      al.remove("F");
      al.remove(2);
      System.out.println("Size of al after deletions: " + al.size());
      System.out.println("Contents of al: " + al);
   }
}

this example is from here.

UPDATE :

When you define your list as:

List myList = new ArrayList(); you can only call methods and reference members that belong to List class. If you define it as:

ArrayList myList = new ArrayList(); you'll be able to invoke ArrayList specific methods and use ArrayList specific members in addition to those inherited from List.

List is not a class it is an interface. It doesn't have any methods implemented. So if you call a method on a List reference, you in fact calling the method of ArrayList in both cases.

Sign up to request clarification or add additional context in comments.

8 Comments

Yes exactly.It's something like List<String> l = new ArrayList...
Could you clarify it in your answer? Specially the part "you will have to use List or ArrayList". For a newbie it can be misunderstood, like if those were totally different types of dynamic arrays.
"You can't make dynamic array in java" - Yes you can, the question is, why would you. ArrayList is just that, a dynamic array, a List backed by an array ;)
@MadProgrammer : Yes exactly that ArrayList is Dynamic Array.
Best practice is List<String> lst = new ArrayList<>;
|
1

Using some kind of List is a better choice, as it basically does what you want (can grow and shrink), in fact, ArrayList is just that, a dynamic array.

You can hand roll your own if you can't use a List using System.arraycopy

For example, this will grow or shrink an array to match the size you provide...

public String[] updateArray(String[] src, int size) {

    String[] dest = new String[size];
    if (size > src.length) {

        System.arraycopy(src, 0, dest, 0, src.length);

    } else {

        System.arraycopy(src, 0, dest, 0, size);

    }

    return dest;

}

Again... List is easier...

Comments

0

Building a dynamic array involves these basic steps:

-Create an array of a fixed capacity.

-When the size of the array (# of elements added) approach the capacity, create a new array (usually doubling the capacity), and copy all the old elements to the new array.

A linked list is the most efficient for your task of building the array (done in O(1) time). However, accessing elements for inserting and deleting in a linked list is not efficient (O(n) time). Imagine having to move through the whole list to get to the last element. Building the dynamic array is less efficient, because of the need to re-size the array as it grows. Inserting and deleting elements is less efficient because of need to move all the elements after to make room or fill the gap. However accessing an element in an array is efficient (O(1) time) and there are big advantages when it comes to sorting.

The Java ArrayList is an implementation of a dynamic array. You could also implement your own.

1 Comment

And I believe the question was how to MAKE a dynamic array, not what Java library can I use for this assignment.
0

If you can't use an ArrayList, or any kind of dynamic list at all, then one solution would be this:

StringBuilder sb = new StringBuilder();
Scanner scanner = new Scanner(System.in);
int j;
while((j=scanner.nextInt()) !=-1){
    sb.append(j + " ");
}
String []numbers = sb.toString().split(" ");
int[] grades = new int[numbers.length];
for(int i=0;i<numbers.length;i++){
    grades[i] = Integer.parseInt(numbers[i]);
}

As you can see, I'm putting the input in a stringbuilder object, then I parse it in an array of strings, and convert that array in an integer array. I hope this helps.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.