2017-10-11 2 views
0

파일에서 단어를 읽고 오름차순으로 정렬하는 기수 정렬을 사용하는 프로그램에서 작업하고 있습니다. 이를 위해 파일의 모든 단어의 길이가 같고 파일에는 문자가 없지만 기호 (기호 없음)가 있는지 확인해야합니다. 정렬 작업이 있지만 문자열 길이가 같은지 또는 기호가 있는지를 알 수 없습니다. 이러한 예외 캐치를 작성하는 방법에 대한 도움을 주시면 감사하겠습니다.기수 정렬 - 예상 예외 호출

이것은 Radix Sort 클래스입니다. 예외를 잡는 데 필요한 두 가지 의견이 있습니다.

import java.util.ArrayList; 
import java.util.Queue; 

public class RadixSort implements RadixSortADT { 


    private ArrayList<String> string; 
    private ArrayList<LinkedQueue<String>> queues; 
    private String result; 


    public RadixSort(ArrayList<String> words) { 
     string = new ArrayList<>(); 
     queues = new ArrayList<>(); 
     initializeList(); 
     initializeWords(words); 
    } 

    public void initializeList() { 
     for(int i = 0; i < 26; i++){ 
      queues.add(new LinkedQueue<String>()); 
     } 

    } 

    public void initializeWords(ArrayList<String> w) { 
     for(int i = 0; i < w.size(); i++){ 
      string.add(w.get(i).toLowerCase()); 
     } 

    } 

    public void sort() { 

     if(string.isEmpty()){ 
      throw new EmptyCollectionException("File"); 
     } 
//Exception needed for string length comparisons 
//Exception needed for nonletters in string 

     for(int j = string.get(0).length()-1; j>= 0; j--){ 
      for(int k = 0; k <string.size(); k++){ 
       char c = string.get(k).charAt(j); 
       queues.get(c-97).enqueue(string.get(k)); 
      } 
      int i = 0; 
      for(int n = 0; n <queues.size(); n++){ 
       while(!queues.get(n).isEmpty()){ 
        string.set(i++, queues.get(n).dequeue()); 
       } 
      } 
     } 
    } 

    public String toString(){ 
     String result = ""; 
     for(String words: string){ 
      result += words + " "; 
     } 
     return result; 
    } 

    public boolean isAlpha(ArrayList<String> string2) { 
     return string2.contains("[a-zA-Z]+"); 
    } 

} 

이이 예외를 포착하기 위해 우리를 위해 제공 한 JUnit 테스트 클래스는

import java.io.File; 
import java.io.FileNotFoundException; 
import java.util.ArrayList; 
import java.util.Scanner; 

public class RadixSortDriver { 

    public static void main(String[] args) throws FileNotFoundException{ 
     int i = 0; 
     ArrayList<String> words = new ArrayList<>(); 
     Scanner scan = new Scanner(System.in); 

     System.out.println("Enter the name of the file to import words"); 
     String filename = scan.nextLine(); 
     //String filename = "four.txt"; 
     Scanner inFile = new Scanner(new File(filename)); 
     while(inFile.hasNext()) { 
      words.add(inFile.nextLine()); 
     } 
     RadixSort r = new RadixSort(words); 
     System.out.println("Unsorted List:\n" + r); 
     r.sort(); 
     System.out.println("\n\nSorted List:\n" + r); 
    } 

} 

기수 정렬 클래스를 생성하기 위해 나를 위해 제공 한 드라이버입니다

import static org.junit.Assert.*; 

import java.io.File; 
import java.io.FileNotFoundException; 
import java.util.ArrayList; 
import java.util.Scanner; 

import org.junit.Test; 

public class RadixSortTest { 

    @Test 
    public void testsort1() throws FileNotFoundException { 
     ArrayList<String> words = new ArrayList<>(); 
     Scanner inFile = new Scanner(new File("four.txt")); 

     while(inFile.hasNext()) { 
      words.add(inFile.nextLine()); 
     } 
     RadixSort evaluator = new RadixSort(words); 
     evaluator.sort(); 
     assertEquals("atom barn crew goat home kite love rain soap xray yarn ", evaluator.toString()); 
    } 

    @Test 
    public void testsort5() throws FileNotFoundException { 
     ArrayList<String> words = new ArrayList<>(); 
     Scanner inFile = new Scanner(new File("fourUpper.txt")); 

     while(inFile.hasNext()) { 
      words.add(inFile.nextLine()); 
     } 
     RadixSort evaluator = new RadixSort(words); 
     evaluator.sort(); 
     assertEquals("atom barn crew goat home kite love rain soap xray yarn ", evaluator.toString()); 
    } 

    @Test(expected=EmptyCollectionException.class) 
    public void testsort7() throws FileNotFoundException { 
     ArrayList<String> words = new ArrayList<>(); 
     Scanner inFile = new Scanner(new File("empty.txt")); 

     while(inFile.hasNext()) { 
      words.add(inFile.nextLine()); 
     } 
     RadixSort evaluator = new RadixSort(words); 
     evaluator.sort(); 
     fail("Empty list Exception not caught"); 


    } 

    @Test(expected=InvalidRadixSortException.class) 
    public void testsort10() throws FileNotFoundException { 
     ArrayList<String> words = new ArrayList<>(); 
     Scanner inFile = new Scanner(new File("error3.txt")); 

     while(inFile.hasNext()) { 
      words.add(inFile.nextLine()); 
     } 
     RadixSort evaluator = new RadixSort(words); 
     evaluator.sort(); 
     fail("Invalid Length Exception not caught"); 


    } 

} 

마지막으로,이 이렇게 생성 된 예외 클래스는 우리가 어떤 예외를 호출 알고있다

예외를 던질
public class InvalidRadixSortException extends RuntimeException 
{ 
    /** 
    * Sets up this exception with an appropriate message. 
    * @param collection the name of the collection 
    */ 
    public InvalidRadixSortException(String error) 
    { 
     super("The list of words contained an invalid " + error); 
    } 

} 
+0

내가 당신의'initializeWords' 방법에있는 모든 단어를 확인할 것입니다. 첫 단어의 길이를 확인한 다음 나머지 단어가 반복되는지 확인하십시오. 동시에 합법적 인 문자 만 포함되어 있는지 확인할 수 있습니다. 'word.toCharArray()'를 사용하여 각 문자열을 문자 배열로 분리 한 다음 반복하여 'c> ='a '&& c <='z ''를 확인하십시오. – teppic

+0

@K. 원더 당신은 당신의 문제를 해결 했습니까? –

답변

0

이 방법을 사용 :

private void validateWords() { 
     int length = string.get(0).length(); 

     for (int j = 0; j < string.size(); j++) { 

      if (string.get(j).length() != length) { 
       throw new InvalidRadixSortException("Invalid String Length"); 
      } 

      if (!string.get(j).matches("[a-zA-Z]+")) { 
       throw new InvalidRadixSortException("Contains Non-Letters"); 
      } 
     } 
    }