Java 使用扫描仪在.txt文件中显示特定单词

Java 使用扫描仪在.txt文件中显示特定单词,java,Java,我陷入困境,需要你的帮助(是的,这是家庭作业),我要做的是让我的代码读取文本文件中的内容,并按特定的单词输出单词。例如,我希望它输出所有以字母“g”开头的单词 如果我没有解释清楚,这里有一个伪代码: BEGIN Get the initial letter from the user While there are more entries in the file Get the next personal name Get the next surname Get the next

我陷入困境,需要你的帮助(是的,这是家庭作业),我要做的是让我的代码读取文本文件中的内容,并按特定的单词输出单词。例如,我希望它输出所有以字母“g”开头的单词

如果我没有解释清楚,这里有一个伪代码:

BEGIN

Get the initial letter from the user

While there are more entries in the file

Get the next personal name

Get the next surname

Get the next year info

If the surname starts with the initial letter

Output the person name, surname and year info

End while

END
到目前为止,我已经成功地完成了这项工作,现在我陷入了正确输出名称的困境。任何帮助或指导都将不胜感激

import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;

public class PrimeMinisters
{
    public static void main(String[] args) throws FileNotFoundException
    {
        // ask the user for the first letter
        Scanner keyboard = new Scanner(System.in);
        System.out.print("What is the first letter? ");
        String input = keyboard.next().toLowerCase();
        char firstLetter = input.charAt(0);

        // open the data file
        File pmFile = new File ("OZPMS.txt");
        // create a scanner from the file
        Scanner pmInput = new Scanner (pmFile);

        // read one line of data at a time, processing each line
        while(pmInput.hasNext())
        {
            String names = pmInput.next();
            System.out.println(names);
        }

        // be polite and close the file
        pmInput.close();
    }
}

我建议使用
nextLine()
而不是
next()
。在此基础上,您将使用
String
startsWith(String-stringsequence)
方法,该方法返回一个布尔值,以获取以您选择的字母开头的所有值:

  while(pmInput.hasNextLine())
        {

            String names = pmInput.nextLine();
            System.out.println(names);
            if(names.startsWith("g")) {
              //the name begins with letter g do whatever
            }
        }

您可以在这里查看字符串的更多方法:

我建议使用
nextLine()
而不是
next()
。在此基础上,您将使用
String
startsWith(String-stringsequence)
方法,该方法返回一个布尔值,以获取以您选择的字母开头的所有值:

  while(pmInput.hasNextLine())
        {

            String names = pmInput.nextLine();
            System.out.println(names);
            if(names.startsWith("g")) {
              //the name begins with letter g do whatever
            }
        }

您可以在此处查看字符串的更多方法:

因为您的要求是查看姓氏的第一个字母,所以在阅读时(在检查用户输入是否是姓氏的第一个字母时)更容易标记每一行。假设行的顺序与上面所述的相同,那么姓氏将是token#2(数组的索引1)


由于您的要求是查看姓氏的第一个字母,因此在阅读时(在检查用户输入是否为姓氏的第一个字母时)更容易标记每一行。假设行的顺序与上面所述的相同,那么姓氏将是token#2(数组的索引1)


个人姓名、姓氏和年份信息都在一行吗?嗨,蒙卡德,是的,每个姓名、姓氏和年份信息都在一行。对不起,如果我没有提到这一点。个人姓名、姓氏和年份信息都在一行吗?嗨,蒙卡德,是的,每个姓名、姓氏和年份信息都在一行。对不起,如果我没提的话。谢谢大卫,我来试试。谢谢大卫,我来试试。