我有一个构造函数,它接受一个字符串作为参数。每当传递到构造函数的字符串包含任何不是“A”、“C”、“G”或“T”的内容时,我想抛出运行时异常。目前,我的代码如下所示:
public DNAStrandNovice(String strand) {
passedStrand = strand;
if (passedStrand.contains("a") || passedStrand.contains("c")
|| passedStrand.contains("g") || passedStrand.contains("t")) {
throw new RuntimeException("Illegal DNA strand");
} else if (passedStrand.contains("1") || passedStrand.contains("2")
|| passedStrand.contains("3") || passedStrand.contains("4")
|| passedStrand.contains("5") || passedStrand.contains("6")
|| passedStrand.contains("7") || passedStrand.contains("8")
|| passedStrand.contains("9") || passedStrand.contains("0")) {
throw new RuntimeException("Illegal DNA Strand");
} else if (passedStrand.contains(",") || passedStrand.contains(".")
|| passedStrand.contains("?") || passedStrand.contains("/")
|| passedStrand.contains("<") || passedStrand.contains(">")) {
throw new RuntimeException("Illegal DNA Strand");
}
}
我觉得这可以以更简洁的方式实现,但我不知道如何实现。现在我只是检查不是大写字母“A”、“C”、“G”或“T”的每个字符并抛出运行时异常,但我觉得这太乏味且糟糕的编程风格。大家有什么想法吗?
最佳答案
消极地检查,而不是积极地检查。
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) != 'A' && str.charAt(i) != 'C'
&& str.charAt(i) != 'G' && str.charAt(i) != 'T') {
throw new IllegalArgumentException("Bad character " + str.charAt(i));
}
}
...或者更短,
for (int i = 0; i < str.length(); i++) {
if (!"ACGT".contains(str.charAt(i))) {
throw new IllegalArgumentException("Bad character " + str.charAt(i));
}
}
关于java - 构造函数抛出运行时异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21471295/