lundi 23 novembre 2020

How to separate items from a file in java

Good afternoon, I am currently trying to read the contents of a file and add them to their respective variables based on how many times they occur. The program is designed to calculate the probability of a boy or girl in a 2 offspring family. BB means 2 boys, GG means 2 girls, and GB or BG is boy and girl. The file`s information is as follows :

BB

GB

GB

BG

GG

GB

GB

GB

GB

GG

Here is what I have coded:

/**
 * Write a description of class Family here.
 *
 * @author (your name)
 * @version (a version number or a date)
 */
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 + "%");
}
}

Aucun commentaire:

Enregistrer un commentaire