创建isValid方法

时间:2014-03-11 20:07:04

标签: java

我正在为Com工作。科学课,它是一个初学者课程,但我没有先前的编码经验,所以我甚至在基础知识上苦苦挣扎。我会问多个问题,我道歉。我们被要求创建一种方法来遍历字符串的所有字符,以查看它们是否为A G C或T.

/**
 *  Determines whether all characters in this strand are valid
 *  ('A', 'G', 'C', or 'T')
 * @return true if all characters are valid, false otherwise
 */
public boolean isValid() {

在课堂上我们得到了这个:

private static int countP(String s) {
    int count = 0;
    int i = 0;
    while (i < s.length())
    {
        if (isLetterP(s.charAt(i)))
        {
            count += 1;
        }
        i += 1;
    }
    return count;
}

我知道我必须使用上述内容,到目前为止我想出了这个:

public boolean isValid() {
    int i = 0;  
    while (i < DNA.length()) {
        if (isValid(DNA.charAt(i)))
        {
            return false;
        }
        i = i + 1;
    } 
    return true;
}

我知道我必须研究if(isValid(DNA.charAT(i)))[行,但我迷路了,我不确定我需要做什么。如果有人不能给我答案,但帮助指导我,那将是非常棒的。

2 个答案:

答案 0 :(得分:1)

public boolean isValid (String s) {
    if (s == null) return false;
    char[] ch = s.toLower().toCharArray();
    for (char c : ch) if (c != 'a' && c != 'c' && c != 'g' && c != 't') return false;
    return true;
}

答案 1 :(得分:0)

您可以使用正则表达式来检查输入字符串是否与某个模式匹配 - 在这种情况下,字符串应该只包含四个字符(A,G,C和T),我也假设它们是小写字母 -

public static boolean isValid (String str) {
    if (str == null) return false;
        // In case lowercase letters are not required you can remove them from the pattern below 
    if (str.matches("^[aAgGcCtT]*$")) return true;
    return false;
}