7 Replies - 1166 Views - Last Post: 01 March 2013 - 06:01 PM Rate Topic: -----

#1 bummer0515  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 5
  • Joined: 01-March 13

problem with threads

Posted 01 March 2013 - 02:51 PM

I am having problem with threads in this project, I have to create a thread that will sort the files and the output should be threadedsort.sort is sorted. I keep getting error message
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at SortTest.main(SortTest.java:24)
Java Result: 1

unsure where my problem is because I am very new to programming and unsure how to fix this. Any help would be greatly appreciated as to why the error message and also guidance on how to fix it.
public class Sort {

    /**
     * You are to implement this method. The method should invoke one or more
     * threads to read and sort the data from the collection of Files. The
     * method should return a sorted list of all of the String data contained in
     * the files.
     *
     * @param files
     * @return
     * @throws IOException
     */
    public static String[] threadedSort(File[] files) throws IOException {
        String[] sortedData = new String[0];

        ArrayList<SortedThread> ThreadArray = new ArrayList<SortedThread>();
        // loop that creates the thread
       
        for (File file : files) {
         SortedThread thread = new SortedThread(getData(file));   
            thread.start();
        }
        // waiting for loops to be finish
        // loop that merges into a single file by calling the join method
        for (SortedThread thread : ThreadArray) {
            if (thread.isAlive()) {
                try {
                    thread.join();
                     sortedData = MergeSort.merge(sortedData, thread.threadData());
                } catch (InterruptedException ex) {
                    Logger.getLogger(Sort.class.getName()).log(Level.SEVERE, null, ex);
                }
            }

        }
        
        //return single value
        return sortedData;
    }

   
    /**
     * This method will read in the string data from the specified file and
     * return the data as an array of String objects.
     *
     * @param file the file containing the String data
     * @return String array containing the String data
     * @throws IOException thrown if any errors occur reading the file
     */
    private static String[] getData(File file) throws IOException {

        ArrayList<String> data = new ArrayList<String>();
        BufferedReader in = new BufferedReader(new FileReader(file));

        // Read the data from the file until the end of file is reached
        while (true) {
            String line = in.readLine();
            if (line == null) {
                // the end of file was reached
                break;
            } else {
                data.add(line);
            }
        }

        //Close the input stream and return the data
        in.close();
        return data.toArray(new String[0]);

    }
}

public class SortedThread extends Thread {

    String[] threadeddata = new String[0];
    String[] data;

    SortedThread(String[] data) {
        this.data = data;

    }

    @Override
    public void run() {
     threadeddata = MergeSort.mergeSort(data);
    }

    public String[] threadData() {
        return threadeddata;



    }
}


public static void main(String[] args) throws IOException {
  
    File[] files = {new File("enable1.txt"), new File("enable2k.txt"), new File("lower.txt"), new File("mixed.txt")};

    // Run Sort.sort on the files and test to ensure the data is sorted
    String[] sortedData = Sort.sort(files);
    for (int i=0; i<sortedData.length-1; i++) {
      if (sortedData[i].compareTo(sortedData[i+1]) > 0) {
        System.out.println("The data returned by Sort.sort is not sorted");
        throw new java.lang.IllegalStateException("The data returned by Sort.sort is not sorted");
      }
    }
    System.out.println("The data returned by Sort.sort is sorted");
    
    // Run Sort.threadedSort on the files and test to ensure the data is sorted
    String[] threadSortedData = Sort.threadedSort(files);
    for (int i=0; i<sortedData.length-1; i++) {
      if (threadSortedData[i].compareTo(threadSortedData[i+1]) > 0) {
        System.out.println("The data return by Sort.threadedSort is not sorted");
        throw new java.lang.IllegalStateException("The data returned by Sort.threadedSort is not sorted");
      }
    }
    System.out.println("The data returned by Sort.threadedSort is sorted");
    
    
  }
  
}

public class MergeSort {
  
  // The mergeSort method returns a sorted copy of the
  // String objects contained in the String array data.
  /**
   * Sorts the String objects using the merge sort algorithm.
   * 
   * @param data the String objects to be sorted
   * @return the String objects sorted in ascending order
   */
  public static String[] mergeSort(String[] data) {

    if (data.length > 1) {
      String[] left = new String[data.length / 2];
      String[] right = new String[data.length - left.length];
      System.arraycopy(data, 0, left, 0, left.length);
      System.arraycopy(data, left.length, right, 0, right.length);
    
      left = mergeSort(left);
      right = mergeSort(right);
    
      return merge(left, right);
      
    }
    else {
      return data;
    }
    
  }
  
  /**
   * The merge method accepts two String arrays that are assumed
   * to be sorted in ascending order. The method will return a
   * sorted array of String objects containing all String objects
   * from the two input collections.
   * 
   * @param left a sorted collection of String objects
   * @param right a sorted collection of String objects
   * @return a sorted collection of String objects
   */
  public static String[] merge(String[] left, String[] right) {
    
    String[] data = new String[left.length + right.length];
    
    int lIndex = 0;
    int rIndex = 0;
    
    for (int i=0; i<data.length; i++) {
      if (lIndex == left.length) {
        data[i] = right[rIndex];
        rIndex++;
      }
      else if (rIndex == right.length) {
        data[i] = left[lIndex];
        lIndex++;
      }
      else if (left[lIndex].compareTo(right[rIndex]) < 0) {
        data[i] = left[lIndex];
        lIndex++;
      }
      else {
        data[i] = right[rIndex];
        rIndex++;
      }
    }
    
    return data;
    
  }
  
}

This post has been edited by GregBrannon: 01 March 2013 - 02:54 PM
Reason for edit:: Fixed code tags.


Is This A Good Question/Topic? 0
  • +

Replies To: problem with threads

#2 GregBrannon  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2205
  • View blog
  • Posts: 5,239
  • Joined: 10-September 10

Re: problem with threads

Posted 01 March 2013 - 03:00 PM

In your main() method, you call Sort.sort(). Do you have such a method?
Was This Post Helpful? 0
  • +
  • -

#3 bummer0515  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 5
  • Joined: 01-March 13

Re: problem with threads

Posted 01 March 2013 - 03:14 PM

View PostGregBrannon, on 01 March 2013 - 04:00 PM, said:

In your main() method, you call Sort.sort(). Do you have such a method?




yes i do, I must of not copied the sort class correctly- however this is correct because I did not needed to use threads on this one, its output say sort.sort is sorted but I am having issue making thread work

 public static String[] sort(File[] files) throws IOException {

        String[] sortedData = new String[0];

        for (File file : files) {

            String[] data = getData(file);
            data = MergeSort.mergeSort(data);
            sortedData = MergeSort.merge(sortedData, data);
        }

        return sortedData;

    }


Was This Post Helpful? 0
  • +
  • -

#4 GregBrannon  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2205
  • View blog
  • Posts: 5,239
  • Joined: 10-September 10

Re: problem with threads

Posted 01 March 2013 - 03:25 PM

It's hard to help you with code that isn't what you've posted. Your error message is pointing to a main() method inside a class called SortTest. You didn't post a class called SortTest.

What's the purpose of the 0-length String array, sortedData[], in the threadedSort() method? That's probably causing your problems when you try to add objects to it, but it's hard to tell. Perhaps you should use an ArrayList or define the length of the array appropriately.
Was This Post Helpful? 0
  • +
  • -

#5 bummer0515  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 5
  • Joined: 01-March 13

Re: problem with threads

Posted 01 March 2013 - 03:38 PM

I am so sorry, I obviously did a terrible job posting the data the main() method is in the public class sortTest. The reasoning for the array in the threadedSort() was to have the threads could be stored into when they are being created. Is this not correct?
Was This Post Helpful? 0
  • +
  • -

#6 bummer0515  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 5
  • Joined: 01-March 13

Re: problem with threads

Posted 01 March 2013 - 05:10 PM

here is the code without the mistakes i made by submitting it first time. I also tried adding the threads created to the array list and still getting the same error message...also unsure if I was adding them correctly

*Edited: correctly tagged code 2 posts down

This post has been edited by pbl: 02 March 2013 - 09:35 PM

Was This Post Helpful? 0
  • +
  • -

#7 g00se  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2831
  • View blog
  • Posts: 11,991
  • Joined: 20-September 08

Re: problem with threads

Posted 01 March 2013 - 05:52 PM

Please Posted Image
Was This Post Helpful? 0
  • +
  • -

#8 bummer0515  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 5
  • Joined: 01-March 13

Re: problem with threads

Posted 01 March 2013 - 06:01 PM

i thought i did sorry!

public class Sort {

/**
* You are to implement this method. The method should invoke one or more
* threads to read and sort the data from the collection of Files. The
* method should return a sorted list of all of the String data contained in
* the files.
*
* @param files
* @return
* @throws IOException
*/
public static String[] threadedSort(File[] files) throws IOException {
String[] sortedData = new String[0];

List<SortedThread> TArray = new ArrayList<SortedThread>();
// loop that creates the thread

for (File file : files) {
SortedThread thread = new SortedThread(getData(file)); 
thread.start();
TArray.add(thread);
}
// waiting for loops to be finish
// loop that merges into a single file by calling the join method
for (SortedThread thread : TArray) {
if (thread.isAlive()) {
try {
thread.join();
sortedData = MergeSort.merge(sortedData, thread.threadData());
} catch (InterruptedException ex) {
Logger.getLogger(Sort.class.getName()).log(Level.SEVERE, null, ex);
}
}

}

//return single value
return sortedData;
}

/**
* Given an array of files, this method will return a sorted list of the
* String data contained in each of the files.
*
* @param files the files to be read
* @return the sorted data
* @throws IOException thrown if any errors occur reading the file
*/
public static String[] sort(File[] files) throws IOException {

String[] sortedData = new String[0];

for (File file : files) {

String[] data = getData(file);
data = MergeSort.mergeSort(data);
sortedData = MergeSort.merge(sortedData, data);
}

return sortedData;

}

/**
* This method will read in the string data from the specified file and
* return the data as an array of String objects.
*
* @param file the file containing the String data
* @return String array containing the String data
* @throws IOException thrown if any errors occur reading the file
*/
private static String[] getData(File file) throws IOException {

ArrayList<String> data = new ArrayList<String>();
BufferedReader in = new BufferedReader(new FileReader(file));

// Read the data from the file until the end of file is reached
while (true) {
String line = in.readLine();
if (line == null) {
// the end of file was reached
break;
} else {
data.add(line);
}
}

//Close the input stream and return the data
in.close();
return data.toArray(new String[0]);

}
}

public class SortedThread extends Thread {


String[] data;

SortedThread(String[] data) {
this.data = data;

}

@Override
public void run() {
data = MergeSort.mergeSort(data);
}

public String[] threadData() {
return data;



}
}

public class MergeSort {

// The mergeSort method returns a sorted copy of the
// String objects contained in the String array data.
/**
* Sorts the String objects using the merge sort algorithm.
* 
* @param data the String objects to be sorted
* @return the String objects sorted in ascending order
*/
public static String[] mergeSort(String[] data) {

if (data.length > 1) {
String[] left = new String[data.length / 2];
String[] right = new String[data.length - left.length];
System.arraycopy(data, 0, left, 0, left.length);
System.arraycopy(data, left.length, right, 0, right.length);

left = mergeSort(left);
right = mergeSort(right);

return merge(left, right);

}
else {
return data;
}

}

/**
* The merge method accepts two String arrays that are assumed
* to be sorted in ascending order. The method will return a
* sorted array of String objects containing all String objects
* from the two input collections.
* 
* @param left a sorted collection of String objects
* @param right a sorted collection of String objects
* @return a sorted collection of String objects
*/
public static String[] merge(String[] left, String[] right) {

String[] data = new String[left.length + right.length];

int lIndex = 0;
int rIndex = 0;

for (int i=0; i<data.length; i++) {
if (lIndex == left.length) {
data[i] = right[rIndex];
rIndex++;
}
else if (rIndex == right.length) {
data[i] = left[lIndex];
lIndex++;
}
else if (left[lIndex].compareTo(right[rIndex]) < 0) {
data[i] = left[lIndex];
lIndex++;
}
else {
data[i] = right[rIndex];
rIndex++;
}
}

return data;

}

}

public class SortTest {

public static void main(String[] args) throws IOException {

File[] files = {new File("enable1.txt"), new File("enable2k.txt"), new File("lower.txt"), new File("mixed.txt")};

// Run Sort.sort on the files and test to ensure the data is sorted
String[] sortedData = Sort.sort(files);
for (int i=0; i<sortedData.length-1; i++) {
if (sortedData[i].compareTo(sortedData[i+1]) > 0) {
System.out.println("The data returned by Sort.sort is not sorted");
throw new java.lang.IllegalStateException("The data returned by Sort.sort is not sorted");
}
}
System.out.println("The data returned by Sort.sort is sorted");

// Run Sort.threadedSort on the files and test to ensure the data is sorted
String[] threadSortedData = Sort.threadedSort(files);
for (int i=0; i<sortedData.length-1; i++) {
if (threadSortedData[i].compareTo(threadSortedData[i+1]) > 0) {
System.out.println("The data return by Sort.threadedSort is not sorted");
throw new java.lang.IllegalStateException("The data returned by Sort.threadedSort is not sorted");
}
}
System.out.println("The data returned by Sort.threadedSort is sorted");


}

} 


Was This Post Helpful? 0
  • +
  • -

Page 1 of 1