2015-10-16 82 views
0

嘿所以我想要得到DNA字符串的GC含量是由C或G字符串中符号的百分比给出的。例如,“AGCTATAG”是.375或37.5%。这是我带来的。我遇到了计算问题,并返回double作为字符串。双字符串Java循环

public static double gcContent(String dna) { 
    //TODO Implement this method 
     double gcContent = 0; 
     double count=0; 
     for (int i = 0; i < dna.length(); i ++) { 
      if (gcContent == dna.length()){ 
       gcContent = (dna.length()/ 2) ; 
      } 
      return double.toString (gcContent); 
     } 
    } 
+0

你的方法总是返回0,你一定不能转换为字符串,如果你的方法返回双。你能否纠正你的例子。 – frifle

+0

好吧,我会把它作为一个双重的,但我怎样才能得到正确的输出? – javakook

回答

1

你不能在原始类型变量中调用toString()。您可以使用:

String.valueOf(gcContent) 
0

如果你坚持使用toString你可以在一个Double对象,像这样的框中的值:

new Double(gcContent).toString(); 

否则最apropriate方式我认为是使用String.format,因为 你可以格式化字符串。例如,如果你想两位,小数点后您有:

return String.format("%.2f", gcContent); 
0

我认为你可以使用Double.toString(GC含量);

2

您的计算没有意义。 你必须迭代你的dna字符串的每个字符并将其与你期望的值char('C'或'G',大写和小写?)进行比较 如果你想返回结果作为字符串,你必须将返回类型也更改为String。

public static String gcContent(String dna) { 
    //TODO Implement this method 
    char c = 'C'; 
    char g = 'G'; 
     double gcContent = 0; 
     double count=0; 
     for (int i = 0; i < dna.length(); i ++) { 

      if (dna.charAt(i) == c || dna.charAt(i) == g){ 
       count++; 
      } 
     } 
     gcContent = count/(double)dna.length(); 
     return String.valueOf(gcContent); 
    } 
+0

jep,就是这样。但是我不会在这个方法中转换为String。分开关注。你有一个方法来完成计算 - 它返回两倍。然后你有一个用户界面或报告或只是一些简单的'System.out ...' - 你转换为字符串。 – frifle

+0

是的,当你需要它作为字符串的时候,这是更简洁的方式来返回double值并在以后转换为字符串。但TS希望“返回字符串”:) – Winusch

0

您需要统计CG字符。然后您可以使用String.format(String, Object...)返回格式化的String。喜欢的东西,

public static String gcContent(String dna) { 
    if (dna == null || dna.isEmpty()) return "0%"; 
    int count = 0; 
    for (char ch : dna.toUpperCase().toCharArray()) { 
     switch (ch) { 
     case 'G': case 'C': 
      count++; 
     } 
    } 
    return String.format("%.1f%%", 100 * (count/(double) dna.length())); 
} 

public static void main(String[] args) { 
    System.out.println(gcContent("AGCTATAG")); 
} 

输出时(如需要)

37.5%