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

Java读取新冠数据文件实现控制台格式化输出(含千分位与制表对齐)

实现方案

核心逻辑说明

  • Java的printf原生支持千分位格式化,格式符%,d即可自动给整数添加千分位分隔符
  • 通过给格式符指定宽度可实现列对齐:比如%-12s代表左对齐、占12个字符宽度的字符串,%,16d代表右对齐、占16个字符宽度、带千分位的整数
  • 读取文件行时需要拆分每行的字段分别格式化,不能直接输出原始行内容

现有代码问题修正

你现有代码存在两个明显错误:

  1. 第一个while (scan.hasNextLine())已经将文件内容全部读取完毕,后续的scan.hasNext()永远返回false,不会执行
  2. System.out.printf("%,d\n" , int);属于语法错误,不能直接用类型关键字int作为输出参数

完整可运行代码

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

public class COVIDdata {
    public static void main(String[] args) {
        // 打印表头
        System.out.printf("%-12s\t%16s\t%16s\t%16s\n", "Name", "Total Cases", "New Cases(7 Days)", "New Cases(24 Hours)");
        System.out.println("-------------------------------------------------------------------------------");
        // 读取文件
        try {
            File file = new File("C:\\Desktop\\COVID-19GlobalData.txt");
            Scanner scan = new Scanner(file);
            while (scan.hasNextLine()) {
                // 拆分每行的字段
                String[] fields = scan.nextLine().split("\\s+");
                String regionName = fields[0];
                int totalCases = Integer.parseInt(fields[1]);
                int newCases7d = Integer.parseInt(fields[2]);
                int newCases24h = Integer.parseInt(fields[3]);
                // 格式化输出,制表符分隔,数值带千分位
                System.out.printf("%-12s\t%,16d\t%,16d\t%,16d\n", regionName, totalCases, newCases7d, newCases24h);
            }
            scan.close();
        } catch (FileNotFoundException e) {
            System.out.println("文件读取错误");
            e.printStackTrace();
        }
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 09:39:01