java - 使用扫描仪显示 .txt 文件中的特定单词

标签 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 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()。然后,您可以使用 StringstartsWith(String stringsequence) 方法返回一个 boolean 值来获取以您选择的字母开头的所有值:

  while(pmInput.hasNextLine())
        {

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

您可以在此处查看更多 String 方法:http://docs.oracle.com/javase/7/docs/api/java/lang/String.html

关于java - 使用扫描仪显示 .txt 文件中的特定单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12287254/

相关文章:

java - Intellij插件开发-访问最近激活的编辑器的内部堆栈

java - 并发线程访问单例

java - 实例初始化 block 和子类

java - 字节数组的十六进制编码形式与转换为字节数组的相同字节数组 “object” 不同。为什么?

java - 我如何枚举Java中父类(super class)的所有子类

java - 比较两个数组的数组元素时, boolean 结果始终返回 true

java - 如何验证没有使用 Mockito 调用特定方法?

java - 可能覆盖数据库表

JavaMail 在使用 JDK 1.7 的 OS X Yosemite 上传输本地 SMTP 速度极其缓慢

java - 无法在小程序中 getInputStream()