如何将String参数传递给void方法?

时间:2016-02-25 10:27:37

标签: java genetics

我需要为我正在学习的课程编写一个Java程序,该程序会查找DNA链中的基因。我遇到的问题是,从测试方法来看,我需要将printAllgenes(a)传递给void printAllgenes方法。在测试方法中,我尝试将'int a'设置为'String a',但在任何一种情况下,编译时都会出现错误,说明void无法转换为int或String。我很确定它很明显,但我对编程很新,所以请原谅我的无知!谢谢。

import java.io.*;
import edu.duke.*;

public class FindProtein {

  public void test() {
    String a = "atg aaa tab tag atg aaa tga aat ag";
    int b = printAllgenes(a);
    System.out.println("DNA string is " + a);
    System.out.println("Gene found is " + b);
  }

  public void printAllgenes(String dna) {
    int sp = 0; //start point
    while (true) {
      int start = dna.indexOf("atg,sp");
      if (start == -1) {
        break;
      }
      int stop = findStopIndex(dna, start + 3);
      if (stop != dna.length()) {
        System.out.println(dna.substring(start, stop + 3));
        sp = stop + 3;
      } else {
        sp = sp + 3;
      }
    }
  }

  public int findStopIndex(String dna, int index) {
    int tga = dna.indexOf("tga", index);
    if (tga == -1 || (tga - index) % 3 != 0) {
      tga = dna.length();
    }
    int taa = dna.indexOf("taa", index);
    if (taa == -1 || (taa - index) % 3 != 0) {
      taa = dna.length();
    }
    int tag = dna.indexOf("tag", index);
    if (tag == -1 || (tga - index) % 3 != 0) {
      tag = dna.length();
    }
    return Math.min(tga, Math.min(taa, tag));
  }
}

2 个答案:

答案 0 :(得分:1)

尝试使用:

 printAllgenes(a); 

因为printAllgenes方法没有任何类型的return语句。

答案 1 :(得分:1)

将返回类型void更改为int无论您想要从printAllgenes(String dns)方法返回什么,它都会返回您的计数。您将获得一个int返回值,它将初始化您在控制台上显示的变量b

public int printAllgenes(String dna){
      int sp = 0; //start point
          while (true){
          int start = dna.indexOf("atg,sp");
             if (start==-1){
                break;
                }   
              int stop = findStopIndex(dna,start+3);
              if (stop!=dna.length()){
                   System.out.println(dna.substring(start,stop+3));
                   sp=stop+3;
                   }
             else{
                 sp=sp+3;
             }        
        } 
        return sp;

    }

现在,您的Test Method实施工作正常......

public void test(){
String a= "atg aaa tab tag atg aaa tga aat ag";
int b = printAllgenes(a);     
System.out.println("DNA string is " +a);
System.out.println("Gene found is "+b);    
 }

谢谢..