好的,所以我有一个程序,它采用三位数字并计算每个数字 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();
不管发生什么,如果我输入多个特定数字(即,如果我输入“222”、“222”,它通过将“2”设置为“100%”来工作,但如果我添加任何其他数字,它会将它们全部设置为零。)
有任何想法吗?