我是学习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
你为什么试图比较Scanner对象和String对象? –
每行有一个代码还是每行都有多个代码? – Bohemian
@Bohemian在这种情况下,每行只有一个代码。 –