2016-09-29 33 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

每行有一個代碼還是每行都有多個代碼? – Bohemian

+0

@Bohemian在這種情況下,每行只有一個代碼。 –

回答

0

你必須要使用掃描儀

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

nextLine方法根據您的線路,你也許想用trim方法上String或使用含有,而不是equals

+0

完美!我還必須擺脫第一個while語句中的inFile.nextLine中的不必要的事情,並且這個工作非常完美!非常感謝! –

0

我認爲通過製作字符串變量來分析行更容易並將其設置爲等於下一行。解析字符串更容易。此外,爲什麼你在文件掃描程序中執行inFile.equals(),以便等於掃描程序對象而不是字符串。

迭代通過像這樣的文件:

雖然(inFile.hadNextLine()){

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

我希望這有助於如果它沒有讓我知道在評論。