通过该程序,我创建了一个数组,并找到字母字符的总数,并找到了A-D中字母总数的百分比。我创建了一种方法,使我能够找到序列中出现的字符的百分比。
例如,对于AABD阵列,字符A将为阵列的50%。我已经测试了此方法,并且在我尝试使用字符D时,它总是有效,直到我莫名其妙地得到26而不是30%的结果,这才使我感到困惑。
我正在使用的数据来自此数据文本,其下方是该字符,它忽略不在A-D之间的字母我正在尝试从该方法中打印出30%的百分比,但是我一直得到26,并且不确定为什么
示例1:
AAAAABBBBBCCCCCDDDDD
AAEBCBAFBBCDCECDADDEFEEFFF
示例2:
AAATAABTBBBBCCCCTCDDTDDD
AASAABBSBBCCSCCDSDDDEEEAEEFBFFFDDF
我的代码:
import java.io.*;
import java.util.*;
public class findSequence {
public static int findPercentages(int perNum, int totalNum) {
int percent = (int) Math.round(perNum * 100.0 / totalNum);
return percent;
}
public static void main(String[] args) {
File inputFile = new File("ShortData.txt");
File outputFile = new File("newDNAOutput");
PrintStream outputStream = null;
Scanner fileScan = null;
try {
fileScan = new Scanner(inputFile);
outputStream = new PrintStream(outputFile);
} catch(Exception e) {
System.out.println("File not found " + e);
System.out.println("Exiting program");
System.exit(1);
}
int numA = 0;
int numB = 0;
int numC = 0;
int numD = 0;
while(fileScan.hasNextLine()) {
String theLine = fileScan.nextLine();
Scanner lineScan = new Scanner(theLine);
if(theLine.length() > 10) {
theLine = theLine.toUpperCase();
char[] dnaArray = new char[theLine.length()];
for(int j = 0; j < dnaArray.length; j++) {
dnaArray[j] = theLine.charAt(j);
}
Arrays.sort(dnaArray);
for(int i = 0; i < dnaArray.length; i++) {
if(dnaArray[i] == 'A') {
numA = numA + 1;
}
if(dnaArray[i] == 'B') {
numB = numB + 1;
}
if(dnaArray[i] == 'C') {
numC = numC + 1;
}
if(dnaArray[i] == 'D') {
numD = numD + 1;
}
}
int totalSum = numA + numB + numC + numD;
int numAPer = findPercentages(numA, totalSum);
int numBPer = findPercentages(numB, totalSum);
int numCPer = findPercentages(numC, totalSum);
int numDPer = findPercentages(numD, totalSum);
outputStream.println(numDPer);
}
}
}
}
您有76个字符的20个D(不包括单词Example#1和Example#2中的两个a)。这是一个百分比:26.31578947368421,大约26%。如果您想获得30%的收入,则应该总共有66个字符。
要获得每一行的百分比,您只需要在while
循环内移动字母计数的声明:
while(fileScan.hasNextLine()) {
int numA = 0;
int numB = 0;
int numC = 0;
int numD = 0;
String theLine = fileScan.nextLine();
if(theLine.length() > 10) {
theLine = theLine.toUpperCase();
char[] dnaArray = new char[theLine.length()];
for(int j = 0; j < dnaArray.length; j++) {
dnaArray[j] = theLine.charAt(j);
}
Arrays.sort(dnaArray);
for (char c : dnaArray) {
switch (c) {
case 'A':
numA += 1;
break;
case 'B':
numB += 1;
break;
case 'C':
numC += 1;
break;
case 'D':
numD += 1;
break;
}
}
int totalSum = numA + numB + numC + numD;
int numAPer = findPercentages(numA, totalSum);
int numBPer = findPercentages(numB, totalSum);
int numCPer = findPercentages(numC, totalSum);
int numDPer = findPercentages(numD, totalSum);
outputStream.println(numDPer);
}
}
这将在每次循环运行时清除值。