You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现带制表符分隔的FlowSample数据解析与格式化输出?

问题

需要实现以下功能:

  • 接收制表符分隔的文本行作为输入(格式示例:USGS 13206000 2021-12-30 14:30 MST 226 P)
  • 按照指定格式打印Flow Sample数据(包含数据输入展示、确认信息、样本摘要三个部分)
  • 为FlowSample类实现单String参数构造方法public FlowSample(String line),已实现多参数构造方法如下:
public FlowSample(String agency, String siteNumber, String timeZone, String qualCode, String timestamp, double flowRate) 
{
    this.agency = agency;
    this.siteNumber = siteNumber;
    this.qualCode = qualCode;
    this.flowRate = flowRate;

    /* Create date formatter and parse */
    // 2021-12-20 14:30
    SimpleDateFormat myFormatter = new SimpleDateFormat("yyy-MM-dd HH:mm");  // 原代码存在格式错误(少一个y)
    // Creating new timezone method and passes TimeZone object into myFormatter
    myFormatter.setTimeZone(TimeZone.getTimeZone(timeZone));

    try 
    {
        // passing in timestamp from constructor
        this.timestamp = myFormatter.parse(timestamp);
    } 
    catch (ParseException e) 
    {
        System.out.println("Error: Unable to parse timestamp: " + timestamp);
        /* Initialize timestamp with the epoch, January 1, 1970, 00:00:000 GMT */
        this.timestamp = new Date(0);
    }
}

困惑点:

  • 不知道如何用制表符分隔处理输入数据
  • 单参数构造方法的编写与调用方式
  • 如何实现指定格式的输出

解决方案

1. 实现单参数构造方法

核心逻辑是拆分制表符分隔的输入字符串,提取字段后调用已有的多参数构造方法:

  • 用String.split("\t")拆分输入行,拆分后数组的索引对应固定字段
  • 对流量字段做类型转换(字符串转double)
  • 加入格式校验,避免非法输入导致后续逻辑出错

代码实现(整合到FlowSample类中):

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

public class FlowSample {
    private String agency;
    private String siteNumber;
    private String qualCode;
    private double flowRate;
    private Date timestamp;

    // 修正后的多参数构造方法(修复年份格式错误)
    public FlowSample(String agency, String siteNumber, String timeZone, String qualCode, String timestampStr, double flowRate) 
    {
        this.agency = agency;
        this.siteNumber = siteNumber;
        this.qualCode = qualCode;
        this.flowRate = flowRate;

        SimpleDateFormat myFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        myFormatter.setTimeZone(TimeZone.getTimeZone(timeZone));

        try 
        {
            this.timestamp = myFormatter.parse(timestampStr);
        } 
        catch (ParseException e) 
        {
            System.out.println("Error: Unable to parse timestamp: " + timestampStr);
            this.timestamp = new Date(0);
        }
    }

    // 单参数构造方法实现
    public FlowSample(String line) {
        String[] fields = line.split("\t");
        if (fields.length != 6) {
            throw new IllegalArgumentException("Invalid input: must contain 6 tab-separated fields");
        }

        // 提取并清理字段(去除可能的首尾空格)
        String agency = fields[0].trim();
        String siteNumber = fields[1].trim();
        String timestampStr = fields[2].trim();
        String timeZone = fields[3].trim();
        double flowRate = Double.parseDouble(fields[4].trim());
        String qualCode = fields[5].trim();

        // 调用多参数构造方法完成初始化
        this(agency, siteNumber, timeZone, qualCode, timestampStr, flowRate);
    }

    // 生成本地时区格式化时间字符串
    public String getLocalFormattedTimestamp(String timeZone) {
        SimpleDateFormat formatter = new SimpleDateFormat("EEE dd MMM yyyy hh:mm:ss a zzz");
        formatter.setTimeZone(TimeZone.getTimeZone(timeZone));
        return formatter.format(timestamp);
    }

    // 生成UTC时区格式化时间字符串
    public String getUtcFormattedTimestamp() {
        SimpleDateFormat formatter = new SimpleDateFormat("EEE dd MMM yyyy hh:mm:ss a zzz");
        formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
        return formatter.format(timestamp);
    }

    // Getter方法,用于输出字段
    public String getAgency() { return agency; }
    public String getSiteNumber() { return siteNumber; }
    public double getFlowRate() { return flowRate; }
    public String getQualCode() { return qualCode; }
}

2. 实现格式化输出逻辑

创建主类处理输入、实例化FlowSample并按照指定格式输出:

import java.util.Scanner;

public class FlowSampleApp {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        // 数据输入区域
        System.out.println("---------------------");
        System.out.println("|     Data Entry    |");
        System.out.println("---------------------");
        System.out.println("Please enter the line of tab separated data:");
        String inputLine = scanner.nextLine();
        System.out.println(inputLine + "\n");

        // 实例化FlowSample对象
        FlowSample sample = new FlowSample(inputLine);
        String inputTimeZone = inputLine.split("\t")[3].trim();

        // 数据确认区域
        System.out.println("---------------------");
        System.out.println("| Data Confirmation |");
        System.out.println("---------------------");
        System.out.println("You entered the following: ");
        System.out.println("Agency: " + sample.getAgency());
        System.out.println("Site Number: " + sample.getSiteNumber());
        System.out.println("Local Timestamp: " + sample.getLocalFormattedTimestamp(inputTimeZone));
        System.out.println("UTC Timestamp: " + sample.getUtcFormattedTimestamp());
        System.out.println("Flow Rate: " + sample.getFlowRate());
        System.out.println("Qualification Code: " + sample.getQualCode() + "\n");

        // 样本摘要区域
        System.out.println("---------------------");
        System.out.println("|  Sample Summary   |");
        System.out.println("---------------------");
        System.out.println("### " + sample.getAgency() + " - " + sample.getSiteNumber() + " ###");
        System.out.println("Timestamp: " + sample.getUtcFormattedTimestamp());
        System.out.println("Flow Rate: " + sample.getFlowRate());

        scanner.close();
    }
}

3. 关键说明

  • 修复了原多参数构造方法中的年份格式错误(将yyy-MM-dd改为yyyy-MM-dd),确保能正确解析4位年份的时间戳
  • 单参数构造方法加入了字段数校验,避免非法输入导致的异常
  • 新增两个格式化时间的方法,分别生成本地时区和UTC时区的指定格式时间字符串,满足输出要求
  • 主类通过Scanner获取用户输入,实例化FlowSample后调用Getter和格式化方法生成符合要求的输出

内容的提问来源于stack exchange,提问作者chriscondreay

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 19:53:14