我有一个接受字符串作为参数的构造函数。每当传递到构造函数中的字符串包含非“ 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));
  }
}

10-07 18:59
查看更多