如何计算百分比

时间:2015-01-20 11:49:17

标签: java servlets percentage

下面的代码从文本文件中获取失败的索引并将其打印到网页,而下面的循环也是如此,但是对于传递。我想计算百分比,我尝试了下面的代码,但它返回0.0%

请帮忙,因为我是新手程序员。

    int i = 0;
    while ((i = (secondLine.indexOf(failures, i) + 1)) > 0) {
        System.out.println(i);
        feedbackString += "<strong style='color: red;'><li>Failed: </strong><strong>" + i + "</strong> - " + "out of " + resultString.length() + " tests.<br>";
    }

    int j = 0;
    while ((j = (secondLine.indexOf(passed, j) + 1)) > 0) {
        System.out.println(j);
        feedbackString += "<strong style='color: green;'><li>Passed: </strong><strong>" + j + "</strong> - Well done.</li>";  
    }

    totalScore = j * 100 / resultString.length();
    System.out.println(totalScore);
    feedbackString += "Your submission scored " + totalScore + "%.<br>";

2 个答案:

答案 0 :(得分:2)

你想让你的师成为浮点师:

totalScore = (double)j * 100 / resultString.length();

假设totalScore是双倍的。

否则,j * 100 / resultString.length()将使用int除法,因此如果resultString.length()&gt; 100,结果为0。

正如汤姆所说,while循环的条件:

while ((j = (secondLine.indexOf(passed, j) + 1)) > 0)

确保它只会在j <= 0时结束。因此,毫无疑问(double)j * 100 / resultString.length()为0。

如果你想要计算通行证数量,你需要第二个计数器:

int j = 0;
int passes = 0;
while ((j = (secondLine.indexOf(passed, j) + 1)) > 0) {
    passes++;
    System.out.println(j);
    feedbackString += "<strong style='color: green;'><li>Passed: </strong><strong>" + j + "</strong> - Well done.</li>";  
}

然后

totalScore = (double)passes * 100 / resultString.length();

答案 1 :(得分:0)

问题是j不是失败的数量,它是失败的索引。因为indexOf返回-1,如果它没有找到该元素并且您使用它来标记搜索结束,它将始终为-1。加1,你总是得到j == 0。

你可以这样做:

String secondLine = "pfpffpfffp";
char failures = 'f';
char passed = 'p';

ArrayList<Integer> failuresList = new ArrayList<Integer>();
ArrayList<Integer> passedList = new ArrayList<Integer>();
String feedbackString = "";

for (int i = 0; i < secondLine.length(); i++) {
  char o = secondLine.charAt(i);
  if (o == failures) {
    failuresList.add(i);
  } else {
    passedList.add(i);
  }
}

int countFailures = failuresList.size();
int countPassed = passedList.size();
int countTotal = countFailures + countPassed;

for (int i = 0; i < failuresList.size(); i++) {
    System.out.println(failuresList.get(i));
    feedbackString += "<strong style='color: red;'><li>Failed: </strong><strong>" + i + "</strong> - " + "out of " + countTotal + " tests.<br>";
}
for (int i = 0; i < passedList.size(); i++) {
    System.out.println(passedList.get(i));
    feedbackString += "<strong style='color: green;'><li>Passed: </strong><strong>" + i + "</strong> - Well done.</li>"; 
}

double totalScore = countPassed * 100.0 / countTotal;
System.out.println(totalScore);
feedbackString += "Your submission scored " + totalScore + "%.<br>";
System.out.println(feedbackString);