请原谅我,我是Java的新手。这是我目前的计划的一部分。在这里,我正在读取一个.txt文件,并将该文件的某些行添加到arrayList(它应该正常工作):
public void actionPerformed(ActionEvent e) {
ArrayList<String> organismsString = new ArrayList<String>();
boolean printLines = false;
StringBuilder organism = new StringBuilder();
if (e.getSource() == openButton) {
returnVal = fileChooser.showOpenDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION) {
file = fileChooser.getSelectedFile();
//File[] file = hairpinFileChooser.getSelectedFiles();
//read file
try {
br = new BufferedReader(new FileReader(
while ((currentLine = br.readLine()) != null) {
if (printLines) {
if (currentLine.startsWith(">")) {
// We have reached the next organism, so stop printing
printLines = false;
// Add the current organism to our collection
organismsString.add(organism.toString());
// Clear the StringBuilder, ready for the next organism
organism.setLength(0);
} else {
// We are still printing the current organism
organism.append(currentLine);
}
}
if (currentLine.startsWith(organismId)) {
// Print this line, and start printing all lines after this (we don't want to append the current line)
//organism.append(currentLine);
printLines = true;
}
}
//Adds the final organism in the .txt file
organismsString.add(organism.toString());
但是现在我想要计算arrayList的每个元素中字母“G”和“C”的频率。
目前,我可以计算ArrayList中所有字母的频率,但不能计算特定字母的频率,也不能计算每个单独元素的频率。我必须实现的代码如下:
char [] c = organism.toString().toCharArray();
int sz = c.length;
int i = 0, j = 0, counter = 0;
for (i = 0; i < sz; i++) {
counter = 0;
for(j=0; j<sz; j++) {
if( j<i && c[i] == c[j]) {
break;
}
if (c[j] == c[i]) {
counter++;
}
if(j == sz-1) {
System.out.println("character " + c[i]+ " is present" +counter+" times");
}
}
}
如果有人对我如何能够实现这一目标有任何帮助或建议,那将非常感激!
希望这一切都有意义,但如果不是,请问任何问题!
非常感谢:)
答案 0 :(得分:0)
你可以有两个int变量,一个用于Cs的数量,一个用于Gs的数量。然后,依次遍历char数组中的元素。如果当前元素等于C,则递增C计数器。如果它等于G,则递增G计数器。
如果您只想要Gs和Cs的总数,那么每次遇到G或C时都要有一个计数器并递增。
答案 1 :(得分:0)
我认为有两种可能的方法。
String.charAt()
。String.replaceAll()
这意味着您要替换所有不是C&#39; C&#39;或者&#39; G&#39;用和空字符串。这将产生一个只有C和G的字符串,您可以调用String.length()
。示例代码:
public static void main(String[] args) throws Exception {
String data = "GGGGGCABCKDJ930495860CCCGCGCGCCCGG";
// Loop counting
int cgCount = 0;
for (int i = 0; i < data.length(); i++) {
if (data.charAt(i) == 'C' || data.charAt(i) == 'G') {
cgCount++;
}
}
System.out.printf("CG Count: %d\r\n", cgCount);
// String.replaceAll with regex pattern
System.out.printf("CG Count: %d\r\n", data.replaceAll("[^CG]", "").length());
}
结果:
CG Count: 20
CG Count: 20