dimanche 23 octobre 2016

If/else if not evaluating correctly? (Reading form text file java) [duplicate]

This question already has an answer here:

I'm trying to read from a text file in java. I need to take in a text document with possible family compositions of two children like "BG" for Boy and Girl or "GG" for two girls. This text file spans thousands of lines with a pretty random and it needs to see what the chances are of getting 2 boys ,2 girls, or 1 boy and 1 girl. For instance the first 5 lines read:

BG

GG

GB

BB

BG

...

My problem is I cannot get it to evaluate which it is and add one to the tally of each as the program runs along. It always evaluates as the default statement. How can I fix this?

import java.util.InputMismatchException;
import java.util.NoSuchElementException;
import java.util.Scanner;
import java.io.IOException;
import java.io.File;

public class ReadingFromText {

    public static void main(String args[])throws Exception, InputMismatchException
   {
       File f = new File("Untitled 1.txt");
        Scanner s = new Scanner(f);

        String b; int boyCOUNT=0; int girlCOUNT=0; int twoGirls=0; int twoBoys=0;int oneBoyoneGirl=0;
        do {
            String a = " "; 
            a = s.nextLine(); 
            System.out.println(a);
            if(a == "BB"){boyCOUNT = boyCOUNT+2;
            twoBoys = twoBoys+1;}
            else if(a == "GG"){girlCOUNT = girlCOUNT+2;
         twoGirls = twoGirls +1;}
            else if(a == "BG"){girlCOUNT = girlCOUNT+1;
          boyCOUNT = boyCOUNT+1;
          oneBoyoneGirl = oneBoyoneGirl +1;}
            else if(s.nextLine() == "GB"){girlCOUNT = girlCOUNT+1;
            boyCOUNT = boyCOUNT+1; 
            oneBoyoneGirl = oneBoyoneGirl +1;}
            else{
                System.out.println("I am bad at this");
            }
        }
        while(s.hasNext());

        System.out.println("2 Girls: " + twoGirls + "\n2 Boys: "+ twoBoys + "\nOne Boy One Girl: " + oneBoyoneGirl);     



        System.out.println(boyCOUNT + " " + girlCOUNT);

        }}

Aucun commentaire:

Enregistrer un commentaire