1

I am writing a program that allows the user to enter up to 1000 String elements from a disk file. This happens in another String array method, it then copies them into another array and then bubblesorts them in the method below. However, I am getting an error due to my new array length expecting 1000 elements and the disk file only putting in, lets say, 50. I think the best way to solve my problem is to create an array that has the same length as the Strings in the disk file. However, I am not sure how to create another array the length of the Disk file input. Any help would be great.

    public static String[]bubbleSort(String[] inputArr) {

    String[] Array2 = new String[inputArr.length];
    for(int i=0;i<inputArr.length;i++)
        Array2[i] = inputArr[i];


    for (int i = 0; i<Array2.length; i++)
    {
      for (int j = 0; j<Array2.length-1; j++)
      {
          if (Array2[j].compareTo(Array2[j+1]) > 0)
          {
            String temp = Array2[j];
            Array2[j] = Array2[j+1];
            Array2[j+1] = temp;
          }
       }
    } 



    return Array2;

}
Steave
  • 29
  • 5
  • 1
    I suggest you show us your code for the disk input since that is what you would need to change. – Peter Lawrey Nov 01 '16 at 16:44
  • 1
    Is that needed just to understand how to copy an array of unknown length into another array? – Steave Nov 01 '16 at 16:45
  • 1
    Possible duplicate of [Make copy of array Java](http://stackoverflow.com/questions/5785745/make-copy-of-array-java) – bradimus Nov 01 '16 at 16:46
  • 1
    @Steave Arrays.copyOf . you have to pass it the new size which you should know when you read the input. – Peter Lawrey Nov 01 '16 at 16:47
  • 1
    @PeterLawrey How do you pass it the new size? Sorry I am pretty new at coding. – Steave Nov 01 '16 at 16:55
  • 1
    @Steave when you call a method, you can give it arguments. The first argument is the array to copy and the second argument is the size. I suggest you read the Javadoc for the method and look at some examples. Google can help you find them. – Peter Lawrey Nov 01 '16 at 16:58

1 Answers1

0

Instead of using an Array you can use an list, may be an array list in which size grows dynamically.

List al = new ArrayList();

for(Strings in files){
al.add(String from file);
}

then based on the Arraylist size you can create an array and copy the elements from the array list or you can directly convert arraylist into an array as shown below.

ArrayList<String> al = new ArrayList<String>();
al.add("Amith");
al.add("Kumar");

String[] arr =(String[]) al.toArray(new String[al.size()]);

Community
  • 1
  • 1