我的代码和/或逻辑出了什么问题?

时间:2011-11-30 05:00:53

标签: java

我在APCS分配方面遇到了一些麻烦。该程序应该从文本文件中读取长度为2的字符串 - test1.txt - 并打印出以下百分比:a)女孩 - 女孩,男孩 - 男孩,男孩 - 女孩或女孩 - 男孩组合,以及b)个别团体总数。

我一直试着用一个小时搞清楚这一点!虽然我对第25行的String声明持怀疑态度,但我无法确认这一点。此外,我担心我搞砸了if-else-if-else循环而没有提示编译错误。

附上源代码供您参考。如果您需要任何其他信息,请不要犹豫。

因为我是一个声誉良好的新用户< 10,请看附图:

http://imgur.com/7HpJF

详细说明不起作用的内容。我拍了一张截图并写了相关评论!

/**
 * Family takes user input of sets of boys, girls, and boys + girls. Results are then
 * tabulated and displayed in a percentage form to the user. The total number of 
 * individuals are also displayed.
 * 
 * @E. Chu
 * @Alpha
 */

import java.util.Scanner;
import java.io.File;
import java.io.IOException;

public class Family {

   public static void main (String[] args) throws IOException {

   int boyCount = 0;
   int girlCount = 0;
   double boyGroupCount = 0.0;
   double girlGroupCount = 0.0;
   int mixedGroupCount = 0;
   int totalPersonCount = 0;
   double totalGroupCount;
   String currentToken = "  ";
   Scanner inFile = new Scanner (new File ("test1.txt"));

   while (inFile.hasNextLine()) {
       currentToken = inFile.nextLine( );
       if (currentToken == "BG") {
          boyCount++;
          girlCount++; 
          mixedGroupCount++; }
       else if (currentToken == "GB") {
           boyCount++;
           girlCount++;
           mixedGroupCount++; } 
       else if (currentToken == "BB") {
          boyCount += 2; 
          boyGroupCount++; }
       else {
          girlCount += 2; 
          girlGroupCount++; } 
   }

   inFile.close();
   totalPersonCount = boyCount + girlCount;
   totalGroupCount = boyGroupCount + girlGroupCount + mixedGroupCount;
   System.out.println("Sample Size: " + totalPersonCount);
   System.out.println("Two Boys (%): " + boyGroupCount / totalGroupCount + "%");
   System.out.println("One Boy, One Girl (%): " + mixedGroupCount + "%");
   System.out.println("Two Girls (%): " + girlGroupCount / totalGroupCount + "%");

} // End of main method.

} // End of class Family.

2 个答案:

答案 0 :(得分:4)

currentToken == "BB"应为currentToken.equals("BB")

请勿使用==使用方法equals代替

答案 1 :(得分:2)

提示:您不想使用==比较字符串,请查看equals方法。