下面我有以下课程。如何获取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());
}
}
答案 0 :(得分:3)
更改throw new InvalidWordException(content, i);
到
throw new InvalidWordException(content.substring(0,i), i);
在Java中,String对象是不可变的。所以你按原样传递原始内容字符串。这就是为什么它没有给你你想要的输出。