【问题标题】:Of the two constructers one works and the other doesn't when the argument is correct当参数正确时,两个构造函数中的一个有效,另一个无效
【发布时间】:2019-11-05 01:16:19
【问题描述】:

我是编程新手。我不明白为什么我用来检查构造函数中字符串参数的字符有效性的构造函数之一不起作用。构造函数应检查输入的字符串是否仅包含字符 G、C、A、T,否则将抛出 IllegalArgumentException

我尝试使用字符数组来检查字符串的有效性,方法是对输入的字符串使用toCharArray() 方法。构造函数适用于无效字符串,但不适用于有效字符串。但我使用的另一个构造函数可以工作。请告诉我为什么第一个没有。

//这是第一个不适合我的构造函数

public class Fragment {
    private String nucleotideSequence;

    public Fragment(String nucleotides) throws IllegalArgumentException {

        char[] validityCheck = nucleotides.toCharArray();
        int validityCounter = 0;

        for (char c : validityCheck) {
            if(c != 'G' || c != 'C' || c != 'A' || c != 'T') {
                validityCounter++;
            }
        }

        if (validityCounter != 0) {
            throw new IllegalArgumentException("Invalid characters present");
        }

        nucleotideSequence = nucleotides;
    }
}

// 这是第二个有效的构造函数

public class Fragment {
    private String nucleotideSequence;

    public Fragment(String nucleotides) throws IllegalArgumentException {

        boolean k = false;

        for(int i = 0; i < nucleotides.length(); i++){

            char lol = nucleotides.charAt(i);
            if(lol=='A'||lol=='G'||lol=='C'||lol=='T'){
                k = true;
            }
            else{
                k = false;
            }

            if(k == false){
                throw new IllegalArgumentException("Dosent work");
            }

            nucleotideSequence = nucleotides;
        }
    }
}

【问题讨论】:

  • 请检查代码格式的正确性,缺少右花括号'}'
  • 您应该考虑重命名validityCounter,以便提示计数错误(如errorCounter)。
  • 考虑以下较短的代码:if (!nucleotideSequence.matches("[AGCT]+")) throw new IllegalArgumentException("Invalid nucleotide sequence");
  • validityCounter 实际上是在计算“无效”,因此它的命名完全符合其用法。名字对于试图理解代码的人来说很重要(甚至可能对你来说,下周),所以我建议修复这个问题。

标签: java


【解决方案1】:

您在构造函数中的问题在于以下 'if' 语句:

if(c != 'G' || c != 'C' || c != 'A' || c != 'T')

这句话总是正确的。所以如下:

    for (char c : validityCheck) {
        if(c != 'G' || c != 'C' || c != 'A' || c != 'T') {
            validityCounter++;
        }
    }

等于:

    for (char c : validityCheck) {
        validityCounter++;
    }

正确的说法是

if(c != 'G' && c != 'C' && c != 'A' && c != 'T') {

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-02-05
    • 2015-03-22
    • 1970-01-01
    • 1970-01-01
    • 2017-11-04
    • 2019-08-28
    • 2023-03-31
    • 1970-01-01
    相关资源
    最近更新 更多