我的任务是阅读包含家庭组合的文本文件,其中可能有孩子的结果。GG = two girls
,GB
和BG = one boy one girl
, BB = two boys
。我应该找到样本的大小,然后打印 3 个可能结果中的每一个的比率。我似乎无法让我的变量在整个循环中递增,它们每次都显示为 0。我检查了调试器,它显示每个文件都被正确读取,但由于某种原因增量不起作用。
这是我的代码:
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
public class Family
{
public static void main(String[] args) throws IOException
{
String token = "";
int girlGirl = 0;
int boyBoy = 0;
int girlBoy = 0;
int sampleSize = 0;
File fileName = new File("test2.txt");
Scanner inFile = new Scanner(fileName);
//read file and get data
while (inFile.hasNext())
{
token = inFile.next();
if(token == "GG")
{
girlGirl++;
sampleSize++;
}
else if(token == "BB")
{
boyBoy++;
sampleSize++;
}
else if(token == "GB")
{
girlBoy++;
sampleSize++;
}
else if(token == "BG")
{
girlBoy++;
sampleSize++;
}
}
inFile.close();
int percentBoyBoy = (boyBoy / sampleSize) * 100;
int percentGirlGirl = (girlGirl / sampleSize) * 100;
int percentGirlBoy = (girlBoy / sampleSize) * 100;
//print results of sample
System.out.println("Sample Size: " + sampleSize);
System.out.println("Two Boys: " + percentBoyBoy + "%");
System.out.println("One Boy One Girl: " + percentGirlBoy + "%");
System.out.println("Two Girls: " + percentGirlGirl + "%");
}//end of main method
}//end of class