java - 查找 JTextfield 字符串中某些字符的出现次数
问题描述
我对编码很陌生,我的程序有问题。我正在尝试运行的程序采用用户在文本字段中提供的 DNA 链(只能包括“A”、“T”、“C”和“G”),然后程序为您提供互补 DNA股。这部分进展顺利,但我还需要它输出原始用户输入中出现“A”、“T”、“C”和“G”的次数(*不是互补链)。
我发现很多帖子说我需要使用计算它的代码(我在最后一个代码块中有它)但我无法让它与程序一起工作,我不知道我会将每个 JLabel 的输出设置为。抱歉,这么长,我只想提供尽可能多的信息。
public void buttonPressed()
{
String str = input.getText().toUpperCase();
for (int i = 0; i <= str.length(); i++) {
char letter = str.charAt(i);
if (letter == 'A' || letter == 'T' || letter == 'C' || letter == 'G') {
str = input.getText().toUpperCase();
str = str.replace("A", "t")
.replace("T", "a")
.replace("C", "g")
.replace("G", "c")
.toUpperCase();
compOutput.setText(str);
}
else {
compOutput.setText("Error: input not in DNA format");
aOut.setText("0");
cOut.setText("0");
gOut.setText("0");
tOut.setText("0");
return;
}
}
}
/**
* This is where I'm having trouble, I can't tell if it's even counting
* the occurrences and if it is, I don't know how to display it in each JLabel.
*
* The JLabels are named aOut, tOut, cOut, gOut
*/
public int countingLetter(String str, char letter) {
int counter = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == letter) {
counter ++;
}
}
return counter;
}
}
解决方案
试试下面的代码。我使用了打印,因为我没有可用的 JLabels 来打印结果。请注意,如果countingLetter()
没有找到字母,它将返回一个 0,因此不需要else
声明。
public void buttonPressed()
{
//String str = input.getText().toUpperCase();
String str = "ACTGTCA";
String originalUserInput = "ACTGTCA";
for (int i = 0; i <= str.length() - 1; i++) {
char letter = str.charAt(i);
if (letter == 'A' || letter == 'T' || letter == 'C' || letter == 'G') {
str = "ACTGTCA";
str = str.replace("A", "t")
.replace("T", "a")
.replace("C", "g")
.replace("G", "c")
.toUpperCase();
}
}
//compOutput.setText(str);
System.out.println("Complement: " + str);
System.out.println("originalUserInput: " + originalUserInput);
System.out.println("A: " + countingLetter(originalUserInput ,'A'));
System.out.println("T: " + countingLetter(originalUserInput ,'T'));
System.out.println("C: " + countingLetter(originalUserInput ,'C'));
System.out.println("G: " + countingLetter(originalUserInput ,'G'));
/*
aOut.setText(countingLetter(originalUserInput ,'A'));
tOut.setText(countingLetter(originalUserInput ,'T'));
cOut.setText(countingLetter(originalUserInput ,'C'));
gOut.setText(countingLetter(originalUserInput ,'G'));
*/
}
/**
* This is where I'm having trouble, I can't tell if it's even counting
* the occurrences and if it is, I don't know how to display it in each JLabel.
*
* The JLabels are named aOut, tOut, cOut, gOut
*/
public int countingLetter(String str, char letter) {
int counter = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == letter) {
counter ++;
}
}
return counter;
}
让我知道它是否有效。