有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java我的代码和/或逻辑有什么问题?

我在APCS任务中遇到了一些问题。程序应该从文本文件test1中读取长度为2的字符串。txt-并打印出:a)女孩、男孩、男孩、女孩或女孩-男孩组合的百分比,以及b)单个组的总数

我已经试了一个小时想弄明白!虽然我对第25行中的字符串声明表示怀疑,但我没有办法证实这一点。此外,我还担心我在没有提示编译器错误的情况下打乱了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) 个答案

  1. # 1 楼答案

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

  2. # 2 楼答案

    currentToken == "BB"应该是currentToken.equals("BB")

    不要使用==而是使用方法equals