1.枚举,常量,结构
确定数量,确定值的几个取值:东西南北,男女,上中下。
enum Gender{male.female}
enum QQStatus{online,offline,hidden}
枚举的用法, QQStatus status = QQStatus,online;
与用字符串相比,枚举的好处就是限定了变量的取值范围,程序处理起来更方便。
常量:
const 类型 常量名 = 常量值;
在定义时赋值,在其他地方 不允许 赋值;
枚举:
让我们定义一种类型,并且在定义这种枚举类型的时候,我们要指定这个类型的所有可能的值
语法:
enum 类型名称 {值1,值2,值3, 。。。 ,值n}
枚举的定义一般和类定义在同一个级别,这样在同个命名空间下的所有的类就都可以使用这个枚举了(方法中/类中也可以)
枚举的作用:
1) 限制用户不能随意赋值,只能在定义枚举时列举的值中选择。
2) 不需要死记每一个词是什么,只需要选择相应的值
3) 注意:定义枚举时,值不能是int类型
枚举类型的变量都可以强制转换成一个int类型
枚举的值在定义时,有默认编号,从0开始
2.字符串与枚举的转换
字符串转换成枚举类型:
(自枚)(Enum.Parse(typeof(自枚),"待转换的字符串"));
3.结构
为什么要用结构?
1)比如,为了存储一个人的信息,要声明一组变量,当要存储N个人的信息时,就要声明N组变量,很麻烦。
2)存储一个人的信息的这几个变量之间没有关系 ,容易记错
语法:
访问修饰符 struct 结构名
{
定义结构成员;
}
定义好一个结构后,就可以直接声明相应的变量了
声明好变量后,通过 变量名.成员名 来访问结构的成员
namespace 结构
{
enum Gender
{
男,
女
}
public struct Person //定义一个名称叫Person的结构
{
public string name;
public Gender sex;
public int age;
}
class Program
{
static void Main(string[] args)
{
Person onePerson;
onePerson.name = "zhangsan";
onePerson.age = 20;
onePerson.sex = Gender.男;
Person secPerson;
secPerson.name = "lisi";
secPerson.age = 22;
secPerson.sex = Gender.男;
}
}
}
练习:
1.定义一个结构叫MyColor,有三个成员,分别为red green blue
声明一个MyColor类型的变量,并对其成员赋值,使MyColor可以表示成一个红色。
namespace 结构练习1
{
//定义一个结构叫MyColor,有三个成员,分别为red green blue
//声明一个MyColor类型的变量,并对其成员赋值,使MyColor可以表示成一个红色。
public struct MyColor
{
public string red;
public string green;
public string blue;
}
class Program
{
static void Main(string[] args)
{
MyColor displayColor;
displayColor.red = "FF";
displayColor.green = "00";
displayColor.blue = "00";
}
}
}
2.定义一个结构类型Person,有三个成员,姓名,性别,年龄,
声明二个Peoson类型变量,分别表示 张三 男 18岁 ;小兰 女 16岁
namespace 结构练习2
{
//定义一个结构类型Person,有三个成员,姓名,性别,年龄,
//声明二个Peoson类型变量,分别表示 张三 男 18岁 ;小兰 女 16岁
public enum Gender
{
男,
女
}
public struct Person
{
public string name;
public Gender sex;
public int age;
}
class Program
{
static void Main(string[] args)
{
Person zsPerson;
zsPerson.name = "张三";
zsPerson.sex = Gender.男;
zsPerson.age = 18;
Console.WriteLine("我叫{0},今年{1}岁了,我是{2}生。", zsPerson.name, zsPerson.age, zsPerson.sex);
Person xlPerson;
xlPerson.name = "小兰";
xlPerson.sex = Gender.女;
xlPerson.age = 16;
Console.WriteLine("我叫{0},今年{1}岁了,我是{2}生。", xlPerson.name, xlPerson.age, xlPerson.sex);
Console.ReadKey();
}
}
}
4.数组
可以一次声明多个同类型的变量,在内存中连续存储
语法:
数据类型[] 数组名 = new 数组类型[数组长度];
例如: int[] score = new int[5];
声明了一个包含5个int类型变量的数组,数组名为:score
5个int类型的变量叫做数组的元素
如何访问数组:通过下标(索引)来访问数组 数组名[下标]
score[0] = 10;
score[4] = 20;
int类型数组一旦声明,里面的每一个元素被初始化为0;
通过 数组名.Length 可以得到数组的长度
a)一次语文测试后,老师让班长统计每一个学生的成绩并计算全班60人的平均成绩,然后把所有成绩显示出来
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace 数组练习1
{
class Program
{
static void Main(string[] args)
{
int sum = 0;
int max;
int[] score = new int[10];
//对数组中元素进行赋值
for (int count = 0; count < score.Length; count++)
{
Console.WriteLine("请输入第{0}个人的成绩:", count + 1);
score[count] = Convert.ToInt32(Console.ReadLine());
}
//求最大值
max = score[0];
for (int count = 0; count < score.Length; count++) // count 可以初始化为1
{
if (score[count] > max)
{
max = score[count];
}
}
//通过一个循环,求一个数组中所有元素的和
for (int count = 0; count < score.Length; count++)
{
sum += score[count];
}
Console.Clear(); //清屏
Console.WriteLine("{0}个人的平均成绩为:{1}", score.Length, sum / score.Length);
//输出数组中每一个元素
for (int count = 0; count < score.Length; count++)
{
Console.WriteLine("第{0}个学生的成绩为:{1}", count + 1, score[count] );
}
Console.WriteLine("最高分为:{0}", max);
Console.ReadKey();
}
}
}
4.1 保存多个值,几乎任意类型都可以声明数组。
int[] nums = new int[3];
int[] nums = {5, 3, 8};
int[] nums = new int[3]{5,3,8};个数和声明数必须一致
int[] nums = new int[5]{5, 3, 8};错误
int[] nums = new int[]{5, 3, 8};正确,可以省略数组个数
使用索引器访问指定编号位置的元素,
访问数组元素:nums[0] , nums[1]
索引从0开始,取到的元素的类型就是数组元素的类型,还可以对数组元素进行赋值
练习:
1.从一个整数数组中取出最大的整数
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace 数组练习01
{
class Program
{
static void Main(string[] args)
{
//找出一个数组中的最大值和最小值
int[] numbers = { 3, 50, 6, 75, 8, 92, 444, 100, 5, 23, 14, 25, 800 };
int max = numbers[0];
int min = numbers[0];
for (int count = 1; count < numbers.Length; count++)
{
if (numbers[count] > max)
{
max = numbers[count];
}
if (numbers[count] < min)
{
min = numbers[count];
}
}
Console.WriteLine("max = {0}", max);
Console.WriteLine("min = {0}", min);
Console.ReadKey();
}
}
}
2.计算一个整数数组的所有元素的和
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace 数组02
{
class Program
{
static void Main(string[] args)
{
//计算一个整数数组的所有元素的和
int[] integer = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 100, -80, 20, -62 };
int sum = 0;
for (int count = 0; count < integer.Length; count++)
{
sum += integer[count];
}
Console.WriteLine("已经数组所有元素的和为:{0}", sum);
Console.ReadKey();
}
}
}
3.将一个字符串数组输出为 | 分割的形式,比如:one|two|three
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace 数组03
{
class Program
{
static void Main(string[] args)
{
//将一个字符串数组输出为 | 分割的形式,比如:one|two|three
string[] array = { "欢", "迎", "来", "到", "黑", "马" };
for (int count = 0; count < array.Length; count++)
{
Console.Write(array[count]);
if (count == array.Length - 1)
{
break;
}
Console.Write("|");
}
Console.ReadKey();
}
}
}
4.将一个整数数组的每个元素进行如下处理:如果元素是正数,
则将这个位置的元素的值加1,如果元素是负数,
则将这个位置的元素的值减1,如果元素是0则不变
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace 数组04
{
class Program
{
static void Main(string[] args)
{
//将一个整数数组的每个元素进行如下处理:如果元素是正数,
//则将这个位置的元素的值加1,如果元素是负数,
//则将这个位置的元素的值减1,如果元素是0则不变
int[] integer = { 10, 20, -10, 5, 0, 3, };
int zero = 0;
for (int count = 0; count < integer.Length; count++)
{
if (integer[count] > zero)
{
++integer[count];
}
else if (integer[count] == zero)
{
}
else
{
--integer[count];
}
}
for (int count = 0; count < integer.Length; count++)
{
Console.WriteLine(integer[count]);
}
Console.ReadKey();
}
}
}
5.将一个字符串数组的元素的顺序进行反转,{"one","two","three","four"}{"four","three","two","one"} 第i个和第length-i-1 个进行交换。
N个数进行交换:
1)交换N/2次
2)在一个循环中,第i个元素与length - i -1 个元素进行交换
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace 数组05
{
class Program
{
static void Main(string[] args)
{
//将一个字符串数组的元素的顺序进行反转,{"one","two","three","four"}{"four","three","two","one"}
//第i个和第length-i-1 个进行交换。
string[] strarray = { "A", "BB", "CCC", "DDDD", "EEEEE", "FFFFFF", "GGGGGGG" };
string temp;
for (int count = 0; count < strarray.Length / 2; count++)
{
//交换
temp = strarray[count];
strarray[count] = strarray[strarray.Length - count - 1];
strarray[strarray.Length - count - 1] = temp;
}
for (int count = 0; count < strarray.Length; count++)
{
Console.WriteLine(strarray[count]);
}
Console.ReadKey();
}
}
}
冒泡排序:让数组中元素,二二比较(第i个与第i+1个)
经过n(i-1)遍二二比较,数组中元素能按照我们预期的规律排序。
要从大到小排序 ,我们进行二二比较的时候用<
10,20,30,40,50,60,70 原始数据7个元素
20,30,40,50,60,70,10 第一趟,比较6次
30,40,50,60,70,20,10 第二趟,比较5次
40,50,60,70,30,20,10 第三趟,比较4次
50,60,70,40,30,20,10 第四趟,比较3次
60,70,50,40,30,20,10 第五趟,比较2次
70,60,50,40,30,20,10 第六趟,比较1次
n个数需要进行n-1 趟比较 (不会主动排最大的数 第一趟排好一个数,只需要排n-1个数)
第t趟比较的次数:元素个数n - t t=i+1 即:n-1-i
for (int i = 0; i < array.length-1; i++)
{
for (int j=0; j<array.length-1-i; j++)
{
if (<) 从大到小
{
交换
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace 冒泡排序
{
class Program
{
static void Main(string[] args)
{
//从大到小排列
int[] scores = { 10, 32, 51, 42, 54, 68, 95, 74, 96, 852, 356, 412, 45, 841, 145 };
for (int count = 0; count < scores.Length - 1; count++)
{
for (int j = 0; j < scores.Length - 1 - count; j++)
{
if (scores[j] < scores[j + 1]) //小于就交换
{
int temp = scores[j];
scores[j] = scores[j + 1];
scores[j + 1] = temp;
}
}
}
for (int count = 0; count < scores.Length; count++) //遍历输出
{
Console.WriteLine(scores[count]);
}
Console.ReadKey();
}
}
}
5. 方法(函数)介绍
a) 函数就是将一堆代码进行重用的机制。函数就是一段代码,
这段代码可能有输入的值(参数),可能有返回值。
一个函数就像一个专门做这件事的人,我们调用它来做一些事情
它可能需要我们提供一些数据给它
它执行完成后可能会有一些执行结果给我们,
它要求我们提供的数据就叫参数
返回的执行结果就叫返回值;
b) Console.ReadLine(); 就是一个有返回结果的函数
Console.WriteLine("hello"); 就是一个有执行参数的函数,
只有告诉WriteLine被打印的数据它才知道如何打印;
int i = Convert.ToInt32("22") 则是一个即有参数又有返回值的函数。
c) 有了函数写代码就像拼积木,C#中的各种各样的技术其实就是通过for if
等这些基础的语法将不同的函数按照一定的逻辑组织起来。
语法:
[访问修饰符][static] 返回值类型 方法名()
{
方法体;
}
一般情况下,
1. 方法一般要定义在 类 中。
2. 如果方法没有返回值,则返回值类型写void。
命名规则:
方法名开头大写,参数名开头小写,参数名,变量名要有意义
方法的调用:
类名.方法名
对于静态方法static,如果在同一个类中,直接写名字调用就行
Return可以立即退出方法
6. 变量的作用域(只讲局部变量)
说出下面代码输出的结果:
namespace ConsoleApplication2
{
class Program
{
//调用者
static void Main(string[]args)
{
intcount = 3;
Test(count); //函数调用
Console.WriteLine(count);
Console.ReadKey();
}
//被调用者
public static void Test(int number)//形参
{
++number;
Console.WriteLine(number);
}
}
}
a) 在方法中定义的变量称为局部变量,作用域从定义开始,到其所在的大括号结束为止。
b) 在一个方法中如何访问另一个方法中的变量
c) 二种解决方法:参数和返回值
在方法名后面的括号内定义变量,叫做定义这个方法的参数,这里定义的变量用来接收调用者传送过来的数据。
注意:如果一个方法有参数,那么调用者就必须传参数,并且传送参数的个数与对应位置上的类型必须一致。
当调用者想访问方法中的变量时,可以通过返回值返回
例如:
string s =Console.ReadLine();
int i = Convert.ToInt32(“22”);
在方法前面定义变量可以收到方法的值,是因为方法中使用了返回值。
所以,当方法返回值的时候,调用方法就要设置变量来接收方法的返回值。
如果一个变量定义在方法外面,类的里面,就叫做类的字段。这个变量就可以被本类所愿方法访问,静态方法只能访问静态字段
由const修饰的常量不能定义静态的。
注意:一个方法只能有一个返回值,
一旦一个方法有返回值,那在这个方法体中,必须通过 return语句返回一个值,值要与返回类型相同。
语法:return 值;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace 返回值
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("请问是否要关闭程序?(y/n)");
strings = ReadAnswer();//接收返回值的变量的类型要与返回值的类型相同
if(s == "y")
{
Console.WriteLine("正在关闭程序...");
}
else
{
Console.WriteLine("程序正在运行,不退出!");
}
Console.ReadKey();
}
public static stringReadAnswer()
{
stringresult = "";
do
{
result = Console.ReadLine();
if(result != "y" && result!= "n")
{
Console.WriteLine("输入有误,请重新输入!");
}
}while(result!= "y" && result != "n");
//当方法执行完成后,result中存储的就是用户输入的y或者n
returnresult;
}
}
}
另一个例子:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace 返回值2
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("请输入二个数字:");
intvar1 = int.Parse(Console.ReadLine());
intvar2 = int.Parse(Console.ReadLine());
intsum = Add(var1, var2);
Console.WriteLine("平均值为:{0}", sum/2);
Console.ReadKey();
}
// 求二个整数的和
public static int Add(int var1,int var2)
{
returnvar1 + var2;
}
}
}
d) 举例:写一个方法 判断一个年份是否是闰年
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace leapyear
{
class Program
{
//请用户输入一个年份,判断是否是闰年
static void Main(string[]args)
{
Console.WriteLine("请输入一个年份:");
intinput;
while(true)
{
try
{
input = int.Parse(Console.ReadLine());
break;
}
catch
{
Console.WriteLine("您的输入有误,请重新输入一个年份!");
}
}
boolresult = LeapYear(input); //函数调用
if(result)
{
Console.WriteLine("{0}年是闰年!", input);
}
else
{
Console.WriteLine("{0}年不是闰年!", input);
}
Console.ReadKey();
}
//判断是否是闰年的函数
public static bool LeapYear(int year)
{
if(year % 400 == 0 || year % 4 == 0 && year % 100 != 0)
{
return true;
}
else
{
returnfalse;
}
}
}
}
练习:
练习1.读取输入的整数,定义成方法,多次调用,如果用户输入的是数字,则返回,
否则提示用户重新输入
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace 练习1
{
class Program
{
static void Main(string[]args)
{
Console.WriteLine("请输入您的年龄:");
intage = ReadInt(); //调用函数
Console.WriteLine("您刚刚输入的年龄为" + age);
Console.WriteLine("请输入您的班级有多少人:");
intpeople = ReadInt(); //调用函数
Console.WriteLine("真不少啊");
Console.ReadKey();
}
public static int ReadInt()
{
intnumber;
while(true)
{
try
{
number = int.Parse(Console.ReadLine());
returnnumber;
}
catch
{
Console.WriteLine("输入有误,请重新输入!");
}
}
}
}
}
练习4.计算输入数组的和: int Sum(int[] values)
当形参是数组的时候,我们传数组名!
7. 思考:
既然Console.WriteLine() 是方法,为什么WriteLine的参数可以是string类型,也可以是int类型,也可以是bool类型,char类型?
方法的重载!
可以定义相同方法,形参的类型要不同!
方法的重载:
一般在同一个类中,方法名相同,并且方法参数个数 不同 或者 对应位置上的 类型 不同,才能构成方法重载。
注意:方法重载和返回值没有关系。
8. 方法返回多个值:
namespace 返回多个值
{
class Program
{
static void Main(string[]args)
{
intnumber;
intresult = Test(out number);
Console.WriteLine("number = {0}, result = {1}", number,result);
Console.ReadKey();
}
public static int Test(outint a)
{
a = 20;
a = a + 1;
returna;
}
}
}
如上代码:
1) 在方法的参数类型前加out,传递参数的时候,也必须在number前加out,表明这个参数不是传入的,而是用来传出值的。
2) 如果参数是以out形式传入的,那么在传入前可以不赋值
3) 在方法中,对于由out修饰的参数,必须得赋值,并且必须在使用前赋值
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace 返回传出
{
class Program
{
static void Main(string[]args)
{
Console.WriteLine("请输入想转换的数据:");
strings = Console.ReadLine();
intresult;
if(int.TryParse(s,outresult) == true)
{
Console.WriteLine("转换成功,转换后的数为:{0}", result);
}
else
{
Console.WriteLine("转换失败!");
}
Console.ReadKey();
}
}
}
编写一个MyTryParse方法,需要用户传入一个字符串,如果这个字符串能转换成int类型,则方法返回true,并且转换后的int类型数据通过方法的参数传出,如果字符串不能转换成int类型,则方法返回false,那么out传出的参数将没有意义,在方法中随意赋值就行了
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace 练习TryParse
{
class Program
{
static void Main(string[]args)
{
Console.WriteLine("请输入字符串:");
stringinput = Console.ReadLine();
intresult;
if(MyTryParse(input, out result))
{
Console.WriteLine("转换成功!" + result);
}
else
{
Console.WriteLine("转换失败!");
}
Console.ReadKey();
}
public static boolMyTryParse(string a,outint b)
{
try
{
b = Convert.ToInt32(a);
returntrue;
}
catch
{
b = 1;
returnfalse;
}
}
}
}
写一个方法,计算一个int类型数组中,每个元素的和,最大值 ,最小值。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace 返回最大值最小值
{
class Program
{
static void Main(string[]args)
{
int[]array = { 0, 12, 32, -20, 36, 512, 412, 32, 21 };
intmax, min, sum;
sum = Test(array, out max,out min);
Console.WriteLine("数组的和为:{0} 最大值为:{1} 最小值为:{2}", sum, max, min );
Console.ReadKey();
}
public static int Test(int[] numbers,out int max, out int min)
{
intsum = 0;
max = numbers[0];
min = numbers[0];
for(int count = 0; count <numbers.Length;count++ )
{
sum += numbers[count];
if(numbers[count] > max)
{
max = numbers[count];
}
if(numbers[count] < min)
{
min = numbers[count];
}
}
returnsum;
}
}
}
out 用于传出值,在方法中,必须对out修饰的参数进行赋值
ref 可以理解成是双向的,可以传入也可以传出
参数传递过程中,如果有out或者ref修饰,那么改变方法中参数变量的值,
调用者方法中变量的值也会相应改变
练习:
重复让用户输入一个数,判断是不是质数(只能被1和自身整除的数),输入q结束,质数的判断用方法来实现。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace 质数判断
{
class Program
{
static void Main(string[]args)
{
stringinput = "";
intnumber = 0;
boolresult;
do
{
Console.WriteLine("请输入一个正整数:");
input = Console.ReadLine();
if(input == "q")
{
Console.WriteLine("程序结束!");
break;
}
try
{
number = int.Parse(input);
result = Prime(number);
if(result == true)
{
Console.WriteLine("{0}是质数", number);
}
else
{
Console.WriteLine("{0}不是质数", number);
}
}
catch
{
Console.WriteLine("输入的数据有误,请重新输入!");
continue;
}
}while(true);
Console.ReadKey();
}
///<summary>
///判断一个数是否是质数
///</summary>
///<paramname="number"></param>
public static bool Prime(int number)
{
for(int count = 2; count < number; count++)
{
if(number % count == 0)
{
returnfalse;//上面的条件一旦成立,说明被2到number-1之间的数除尽了,所以不是质数
}
}
//循环执行完毕,也就说明上面的条件不成立,说明是个质数
returntrue;
}
}
}