我正在尝试创建一个程序,它可以更改数组中字符串的所有字母

时间:2018-04-06 16:01:44

标签: java

这是我第一次进入这个网站,我不是英语,因为我的英语很糟糕,我开始编程一个或几个月前,如果我说一些愚蠢的事情,那就太麻烦了。 我正在尝试创建一个程序,你必须插入由字母AGTC生成的字符串,当我插入一个点时它将停止询问字符串。这个程序改变了这个字母(A为T,T为A,G为C,C为G),当字母改变时,它打印所有反转的字符串,这里我举一个例子:

输入: ATGCATGC GTCGTGA 。 输出: GCATGCAT(倒置) TCACGAC(倒置)

问题出现在我要打印字符串的最后一个循环中。 钯:我想尽可能多地提供信息,让你很容易,这是我第一次,PLZ明白了。

    Scanner t = new Scanner(System.in);
    String [] cad = new String [20]; //Strings which we are going to enter (made by AGTC..);
    String [] fin = new String [20]; //Strings which I want to print 
    int [] length = new int [20]; //I took the lenght of ever string to change the letters from each one.
    boolean [] ver = new boolean [20]; //This boolean is to stop the loop, when I type a point the loop must stop.
    System.out.println("Put ADN chains (Finish with a point)");
    int count = 0;
    for (int i=0; i<20; i++) {
        cad[i]=t.nextLine();
        cad[i]=cad[i].toUpperCase();
        length [i] = cad[i].length();
        fin[i]=cad[i].replaceAll("T","a");
        fin[i]=fin[i].replaceAll("A","t");
        fin[i]=fin[i].replaceAll("G","c");
        fin[i]=fin[i].replaceAll("C","g");

        ver [i] = cad[i].equals("."); //The way the loop should stop.
        if (ver[i]==true){
            break;
        }
        if (ver[i]==false){
            count++; //I made this counter only to know how many strings they have inserted.
        }
    }
    for (int i=0;i<count; i++) {
            for (int j=0;j<length[i]; i--) { //Here is the main problem, I got the chain with the letters changed but I need to invert the chain.
            System.out.println(fin[i].toUpperCase());     
        }
    }

1 个答案:

答案 0 :(得分:1)

有一种称为 replaceAll 的字符串方法,您可以使用它来替换字符串的部分内容,例如:

  "ATGCATGC GTCGTGA .".replaceAll ("A", "T");

在upcomming java9中,有一个jshell,非常适合测试这些东西。

-> "ATGCATGC GTCGTGA .".replaceAll ("A", "T")
|  Expression value is: "TTGCTTGC GTCGTGT ."
|    assigned to temporary variable $85 of type String

所以在第一眼看来,好像在链中调用4个这样的方法会得到结果,但是:

-> "ATGCATGC GTCGTGA .".replaceAll ("A", "T").replaceAll ("T", "A").replaceAll ("G", "C").replaceAll ("C", "G")
|  Expression value is: "AAGGAAGG GAGGAGA ."
|    assigned to temporary variable $1 of type String

转换后的As从下一个转换中重新转换,但我们可以使用技巧 - 转换为小写:

-> "ATGCATGC GTCGTGA .".replaceAll ("A", "t").replaceAll ("T", "a").replaceAll ("G", "c").replaceAll ("C", "g")
|  Expression value is: "tacgtacg cagcact ."
|    assigned to temporary variable $2 of type String

最后,调用大写的一切:

-> String dna = "ATGCATGC GTCGTGA .".replaceAll ("A", "t").replaceAll ("T", "a").replaceAll ("G", "c").replaceAll ("C", "g").toUpperCase ()
|  Modified variable dna of type String with initial value "TACGTACG CAGCACT ."