好的,所以我有一个程序需要三位数字,并计算每个数字0-9在所有输入的数字中出现的次数,并给出每个数字的百分比。出于某种原因,当我输入“111”或“222”之类的数字时,它可以正常工作并将该数字百分比设置为100%。如果我添加另一个数字,如“123”,它会将所有百分比作为零返回。这是代码:
声明:
private List<PickThreeNumbers> numberList = new ArrayList();
private static int[] timesOccured = {0,0,0,0,0,0,0,0,0,0};
private static double[] percentages = {0,0,0,0,0,0,0,0,0,0};
private static int totalNumbers;
private DecimalFormat dm = new DecimalFormat("0.00");
private static String percentage, timesOccuredString;
这计算每个数字出现在数字列表中的次数:
private void calculateTimesOccured(){
resetAllCalculations();
for(int i = 0; i < numberList.size();i++){
for(int r = 1; r <=3; r++){
for(int b = 0; b <=9; b++){
if (numberList.get(i).getSingleDigit(r) == b){
timesOccured[b]+=1;
}
}
}
}
}
然后,计算百分比:
private void calculatePercentages(){
for(int w = 0; w < timesOccured.length; w++){
totalNumbers+=timesOccured[w];
}
for(int e = 0; e < percentages.length; e++){
percentages[e] = timesOccured[e] / totalNumbers;
percentages[e]*=100;
}
}
然后,这会将百分比返回到主要活动:
public String getPercentage(int digit){
for(int t = 0; t<percentages.length;t++){
if(digit == t){
percentage= dm.format(percentages[t]);
}
}
return percentage;
}
最后,这是主要活动类中动态生成表的方法:
percentages.setStretchAllColumns(true);
percentages.removeAllViews();
for(int i = 0; i <=9; i++){
TableRow tr = new TableRow(this);
TextView digit = new TextView(this);
TextView timesOccured = new TextView(this);
TextView percent = new TextView(this);
digit.setText(String.valueOf(i)+":");
timesOccured.setText(numbers.getTimesOccuredString(i));
percent.setText(numbers.getPercentage(i));
digit.setTextColor(Color.WHITE);
timesOccured.setTextColor(Color.WHITE);
percent.setTextColor(Color.WHITE);
tr.addView(digit);
tr.addView(timesOccured);
tr.addView(percent);
if(i%2 != 0){
tr.setBackgroundColor(Color.parseColor("#333333"));
}else{
tr.setBackgroundColor(Color.parseColor("#444444"));
}
percentages.addView(tr);
}
这是主要活动类中的声明:
TableLayout numbersEntered, percentages, recommendedNumbers;
NumberHandler numbers;
在OnCreate方法中使用它:
numbersEntered = (TableLayout)findViewById(R.id.enteredNumbersTable);
percentages = (TableLayout)findViewById(R.id.percentagesTable);
recommendedNumbers=(TableLayout)findViewById(R.id.recNumbersTable);
numbers = new NumberHandler();
Nomatter会发生什么,如果我输入多个特定数字(例如,如果我输入“222”,“222”,它的工作原理是将“2”设置为“100%”,但如果我添加任何其他数字它将它们全部设为零。)
有什么想法吗?
答案 0 :(得分:1)
在calculatePercentages中,您需要将被分割的数字转换为双精度数。你正在做整数数学,要么是0还是1。
percentages[e] = (double)timesOccured[e] / (double)totalNumbers;