請原諒我,我是Java新手。這是我目前的計劃的一部分。在這裏,我讀txt文件,並添加文件的某些行到一個ArrayList(工作,因爲它應該):獲取ArrayList中每個元素的特定字符的頻率<String>
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());
但是我現在想算字母的頻率「G」和「 C「在arrayList的每個元素中。
目前我能夠統計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");
}
}
}
如果任何人有我怎麼可能能夠進而達到這一點,將不勝感激任何幫助或建議!
希望這一切都是有道理的,但如果沒有請只問任何問題!
非常感謝:)
你只是想只計算大寫字母 「G」 和/或 「C」?或者你還想包括小寫字母嗎? – Shar1er80
不只是大寫的。我希望所有的資本G和C的總頻率對於數組列表的每個元素都一致,但是難以實現這一點,儘管我知道這可能是一個簡單的解決方案:) – Matt