首页 > 解决方案 > 如何从java中的一组数据中获取最后一句话?

问题描述

我有一组数据,包含多个单词和数字...如何从一组数据中获取最后一个单词?

数据示例:

1995 年 6 月 987 65 艾莉森

1995 年 7 月 973 85 艾琳

1995 年 8 月 929 120费利克斯

1995 年 8 月 968 95 亨贝托

在示例中,如何获取粗体字(位于第四列)?

String year = scanner.nextLine().substring(0,4);
String month = scanner.nextLine().substring(5, 8);
String pressure = scanner.nextLine().substring(9, 12);
String windSpeed = scanner.nextLine().substring(13, 15);

System.out.println(scanner.nextLine().substring(scanner.nextLine().lastIndexOf(" " + 1))); //want the fourth column

标签: java

解决方案


试试这个:输入文件内容:

1995 Jun 987 65 Allison
1995 Jul 973 85 Erin
1995 Aug 929 120 Felix
1995 Aug 968 95 Humberto

阅读文件:

public static void main(String[] args) throws FileNotFoundException {
        Scanner scanner = new Scanner(new File("D:\\tester.txt"));
        while (scanner.hasNextLine()) {
            String line = scanner.nextLine();
            String[] splited = line.split("\\s+");
            System.out.println("splited = " + splited[splited.length - 1]);
        }
        
    }

输出:

splited = Allison
splited = Erin
splited = Felix
splited = Humberto

推荐阅读