C#源代码计算器

本文介绍了一个使用C#编写的程序,用于统计.cs和.java文件中的总行数、空白行数、注释行数和代码行数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

要求:用C#编写出一个可以算出.cs或者.java文件里的总行数,空白行数,注释行数,代码行数

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace ConsoleApplication2
{
    class Program
    {
        static int commentLineCount = 0, allLineCount = 0, blankLineCount = 0, codeLineCount = 0;

        static void Main(string[] args)//主函数
        {
            Console.WriteLine("请输入文件路径:");
            String path = Console.ReadLine();
            count(path);
            Console.WriteLine("总行数为{0}\n空白行数为{1}\n注释行数为{2}\n代码行数为{3}", allLineCount = blankLineCount + commentLineCount + codeLineCount, blankLineCount, commentLineCount, codeLineCount);
            Console.WriteLine("请输入任意键继续");
            Console.ReadKey();
        }
        static void count(string file)
        {

            try
            {
                //读取文件
                FileStream aFile = new FileStream(file, FileMode.Open);
                StreamReader sr = new StreamReader(aFile);
                string line = sr.ReadLine();
                //开始判断
                while (line != null)
                {
                    if (line.Trim() != "" && !(line.Trim().StartsWith(@"//")))
                    {
                        codeLineCount++;
                    }
                    else if (line.Trim().StartsWith(@"//") || line.Trim().StartsWith(@"///"))
                    {
                        commentLineCount++;
                    }
                    else
                    {
                        blankLineCount++;
                    }

                    line = sr.ReadLine();
                }
                sr.Close();
            }
            catch (IOException e)
            {
                Console.WriteLine("An IO exception has been thrown!");
                Console.WriteLine(e.ToString());
                return;
            }
        }
    }

}

异常处理:



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值