2016-09-29 1 views
1

私はJavaを学ぶのが初めてで、この特定の課題について多くの問題を抱えています。通常、私は少しの研究の後で解決策を見つけ出すことができますが、これは私に困ってしまいます。 "G"と "B"の文字の組み合わせ(GG、GB、BB、BGなど)の異なるファイルを読み込むプログラムです。ファイルの行数とインスタンスの数を数えなければなりませんそれらの組み合わせのそれぞれがポップアップします。どんな助けでも大歓迎です! 私はすべての記事を検索しようとしましたが、何か試しましたが、今では私のプログラムが実行されないようです。スキャナクラスを使用してテキストファイルをスキャンし、特定のフレーズを選んで数えますか?

ソースコード:

import java.util.Scanner; 
import java.io.File; 
import java.io.IOException; 
public class Family 
{ 
    public static void main(String[] args) throws IOException 
    { 
     //define variables 
     String lineRead = ""; 
     int numberLines = 0; //# of lines 
     int bothMales = 0; //# of houses with both males 
     int bothFemales = 0; //# of houses with both females 
     int oneEach = 0; //#of houses with one male and one female 
     File fileName = new File("test1.txt"); 
     Scanner inFile = new Scanner(new File("test1.txt")); 

     while (inFile.hasNextLine()) 
     { 
      numberLines++; 
      inFile.nextLine(); 
      Scanner check = new Scanner(inFile.nextLine()); 
      while(check.hasNext()) 
      { 
       if (inFile.equals("BB")) 
       { 
        bothMales++; 
       } 
       else if (inFile.equals("GG")) 
       { 
        bothFemales++; 
       } 
       else if ((inFile.equals("GB")) || (inFile.equals("BG"))) 
       { 
        oneEach++; 
       } 
      } 
     } 


     System.out.println("Sample Size: " + numberLines); 
     System.out.println("Two Boys: " + bothMales); 
     System.out.println("Two Girls: " + bothFemales); 
     System.out.println("One Girl and One Boy: " + oneEach); 


    }//end main method 
}//end class 
+0

ScannerオブジェクトとStringオブジェクトを比較しようとしているのはなぜですか? –

+0

各行には1つのコードがありますか、または各行に複数のコードがありますか? – Bohemian

+0

@Bohemianこの場合、各行には1つのコードしかありません。 –

答えて

0

あなたのラインに応じて、スキャナ

 while(check.hasNext()) 
     { 
      String line = check.nextLine(); 
      if (line.equals("BB")) 
      { 
       bothMales++; 
      } 
      // etc 
     } 

nextLine方法を使用する必要があり、あなたは多分Stringまたは使用含まれている上trimメソッドを使用したいです、むしろequals

+0

完璧!私はまた、最初のwhileステートメントでuneccessary inFile.nextLineを取り除かなければなりませんでしたが、これは完全に機能しました!どうもありがとうございます! –

0

私はそれがストリングvariaそれを次の行に等しく設定します。文字列を解析する方が簡単です。また、ScannerファイルにinFile.equals()を実行して、Scannerオブジェクトが文字列でないようにする理由このようなファイルを使用して

反復:

ながら(inFile.hadNextLine()){

String nxtline = scan.nextLine(): 
If(nxtLine.equals("BB") 
    Your code here repeat this for your other if statements. 

私はそれは私がコメントで知らせなかった場合、これは助けを願っています。

関連する問題