2017-01-09 65 views
2

這裏我有以下類。如何讓我的wordValidation()方法提供wordContent以僅將輸出提供給找到的單詞及其索引。 對於使用我的測試程序進行輸出的示例,如果我有一個像「BCGAYYY」這樣的輔音字,在這種情況下如何提供輸出到錯誤的字符A(因爲A不是consonat),以獲得像「BCGA 「+索引?僅返回字符串內容到一個特定的索引

我有方法wordValidation()下面然而,這提供了全詞及其索引...

public abstract class Words { 
    private String wordDetail; 
    private String wordContent; 

    public Words(String wordDetail, String wordContent) throws InvalidWordException{ 
    this.wordContent = wordContent; 
    this.wordDetail = wordDetail; 
    wordValidation(); 



    } 

    public String getWordDetail() { 
     return this.wordDetail; 
    } 

    public String getWordContent() { 
     return this.wordContent; 

    } 

    public abstract String AcceptedCharacters(); 

    public void wordValidation() throws InvalidWordException{ 

      String content = getWordContent(); 
     String theseletters = this.AcceptedCharacters(); 


     for (int i = 0; i < content.length(); i++) { 
      char c = content.charAt(i); 
      if (theseletters.indexOf(c) == -1) { 
       throw new InvalidWordException(content, i); 

      } 
     } 

    } 

    public String toString(){ 
    return getWordDetail() + getWordContent(); 

    } 

經過異常

public class InvalidWordException extends Exception { 

    public InvalidWordException (String wordContent, int theIndex) { 
     super("Wrong Word" + wordContent + theIndex); 
    } 


} 

具體類1

public class Vowels extends Words { 
    private String validVowels; 

    public Vowels(String wordDetail, String wordContent) throws InvalidWordException { 
     super(wordDetail, wordContent); 
    } 

    @Override 
    public String AcceptedCharacters() { 
     return validVowels = "AEIOU"; 
    } 

    public static void main(String[] args) { 
     try { 
      Vowels vowel = new Vowels("First Vowel Check" ,"AEIOXAEI"); 
     } catch (InvalidWordException ex) { 
      System.out.println(ex.getMessage()); 
     } 
    } 

} 

具體類2

public class Consonants extends Words { 
    private String validConsonants; 
    public Consonants(String wordDetail, String wordContent) throws InvalidWordException{ 
     super(wordDetail, wordContent); 
    } 

    @Override 
    public String AcceptedCharacters() { 
     return validConsonants ="BCDFGHJKLMNPQRSTVXZWY"; 
    } 
    public static void main(String[] args) { 
     try { 
      Consonants consonants = new Consonants("First Consonant Check","BCGAYYY"); 
     } catch (InvalidWordException ex) { 
      System.out.println(ex.getMessage()); 
     } 

    } 
} 

測試程序

public static void main(String[] args) { 
     try { 
      Consonants consonants = new Consonants("First Consonant Check","BCGAYYY"); 
     } catch (InvalidWordException ex) { 
      System.out.println(ex.getMessage()); 
     } 

    } 

回答

3

變化throw new InvalidWordException(content, i);

throw new InvalidWordException(content.substring(0,i), i);

在Java中,String對象是不可改變的。所以你原樣傳遞原始內容字符串。這就是爲什麼它沒有給你你想要的輸出。

+2

謝謝你很好。 – blueGOLD

相關問題