下午好,我正在尝试读取一个文件的内容,并根据它们出现的次数将它们添加到各自的变量中。这个程序是用来计算一个男孩或女孩在一个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 + "%");
}
}
1条答案
按热度按时间rbl8hiat1#
我不知道这是否回答了你的问题,但据我所知,你想分开文本文件中的每一行。如果是这种情况,您可以编写一个switch语句,它有两种情况:a和b。你需要一个循环来遍历一行中的每个字符:
p、 s:我不是Maven,我只是个学生。