下午好,我目前正在尝试读取一个文件的内容,并根据它们出现的次数将它们添加到各自的变量中。该程序旨在计算 2 个后代家庭中男孩或女孩的概率。 BB 表示 2 个男孩,GG 表示 2 个女孩,GB 或 BG 表示男孩和女孩。文件信息如下:
BB
GB
GB
BG
GG
GB
GB
GB
GB
GG
这是我编码的内容:
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
public class Family
{
public static void main (String args[]) throws IOException {
//variables defined
int numGB = 0;
int numBG = 0;
int numGG = 0;
int numBB = 0;
int totalNum = 0;
double probBG;
double probGG;
double probBB;
String token ="";
int spaceDeleter = 0;
int token2Sub = 0;
File fileName = new File ("test1.txt");
Scanner in = new Scanner(fileName); //scans file
System.out.println("Composition statistics for families with two children");
while(in.hasNextLine())
{
token = in.next( ); //recives token from scanner
if(token.equals("GB"))
{
numGB = numGB + 1;
}
else if(token.equals("BG"))
{
numBG = numBG + 1;
}
else if(token.equals("GG"))
{
numGG = numGG + 1;
}
else if(token.equals("BB"))
{
numBB = numBB + 1;
}
else if(token.equals(""))
{
spaceDeleter =+ 1; //tried to delete space to no avial
}
else
{
System.out.println("Data reading error");
}
}
in.close(); //closes file
totalNum = numBB + numGG + numBG + numGB; // calculates total num of tokens
probBG = (numBG + numGB) / totalNum; //Probability of boy and girl
probBB = numBB / totalNum; // Probability of Boy
probGG = numGG / totalNum; //Probability of girl
System.out.println("Total number of families: " + totalNum); //print results to user
System.out.println("");
System.out.println("Number of families with");
System.out.println("\t 2 boys: " + numBB + " represents " + probBB + "%");
System.out.println("\t 2 girls: " + numGG + " represents " + probGG + "%");
System.out.println("\t 1 boy and 1 girl: " + (numBG + numGB) + " represents " + probBG + "%");
}
}
我不知道这是否能回答您的问题,但据我了解,您想要分隔文本文件中的每一行。如果是这种情况,您可以编写一个包含两种情况的 switch 语句,A 和 B。您希望循环遍历一行中的每个字符:
for(int i = 0; i<2; i++){
switch(token.charAt(i)){
case 'G':
<Some variable>
break;
case 'B':
<Some variable>
break;
}
}
P.S: 我不是专家,我只是个学生