2016-09-29 62 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. 

我希望这有助于如果它没有让我知道在评论。