您的位置:首页 > 编程语言 > C#

C#课后题+上机(四)

2016-04-01 21:18 393 查看
(1)输入一个由若干个字符组成的字符串,写一个静态方法,方法中使用输出参数输出其中的大写字母、小写字母、数字和其他字符的个数

代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string s=Console.ReadLine();
char [] a=s.ToCharArray();
int num1,num2,num3,num4;
MyClass.TongJi(out num1, out num2, out num3, out num4, a);
Console.WriteLine("大写字母:{0} 小写字母:{1} 数字:{2} 其他:{3}", num1, num2, num3, num4);
Console.ReadKey();
}
}
class MyClass
{
public static void TongJi(out int num1,out int num2,out int num3,out int num4,params char[] a)
{
num1 = num2 = num3 = num4 = 0;
for (int i = 0; i < a.Length; i++)
{
if (a[i] >= 'A' && a[i] <= 'Z')
num1++;
else if (a[i] >= 'a' && a[i] <= 'z')
num2++;
else if (a[i] >= '0' && a[i] <= '9')
num3++;
else
num4++;
}
}
}
}




上机:

(2)设计一个类,该类中有一个方法,该方法使用Random类随机产生10个3位数字的随机数,并把产生的10个随机数存入数组中,然后在另一个类中输出这10个数。

代码:

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

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int[] a=new int[10];
a=RandomNum.produce();
foreach (int item in a)
Console.Write(item + " ");
Console.ReadKey();
}
}
class RandomNum
{
public static int[] produce()
{
Random rdm=new Random();
int[] a=new int[10];
for (int i = 0; i < 10; i++)
{
a[i]=rdm.Next(900)+100;
}
return a;
}
}
}




(3)编写一个名称为MyClass的类,在该类中编写一个方法,名称为CountNum,返回值为整型,参数又两个,第一个参数可以是字符串、整型、单精度、双精度,第二个参数为字符,方法功能返回第二个参数在第一个参数中出现次数。例如,CountChar(“6221982”,‘2’)返回值为3

代码:

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

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(MyClass.CountChar("stringstringss", 's'));
Console.WriteLine(MyClass.CountChar(12345552, '5'));
Console.WriteLine(MyClass.CountChar(123.2334, '3'));
Console.ReadKey();
}
}
class MyClass
{
public static int CountChar(string s,char c)
{
int count=0;
char[] ch = s.ToCharArray();
for (int i = 0; i < ch.Length; i++)
{
if (ch[i] == c)
count++;
}
return count;
}
public static int CountChar(int n, char c)
{
int count = 0;
char[] ch = n.ToString().ToCharArray();
for (int i = 0; i < ch.Length; i++)
{
if (ch[i] == c)
count++;
}
return count;
}
public static int CountChar(float f, char c)
{
int count = 0;
char[] ch = f.ToString().ToCharArray();
for (int i = 0; i < ch.Length; i++)
{
if (ch[i] == c)
count++;
}
return count;
}
public static int CountChar(double d, char c)
{
int count = 0;
char[] ch = d.ToString().ToCharArray();
for (int i = 0; i < ch.Length; i++)
{
if (ch[i] == c)
count++;
}
return count;
}
}
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: