C# basic introduction day four

Opening preface: Due to the end of the year, there was too much work at work, and the company was dragged out to socialize on weekends. This may be an obstacle for my age to learn something by myself. From today, I will speed up my learning progress.

One: Exception catching
Exception: There is no error in the syntax. When the program is running, an error occurs due to some reasons, which causes the program to not run normally.
In order to make the program more healthy and useful, we should use try-catch
syntax
try
{
code that may be abnormal;
}
catch
{
code that is executed after an exception;
}

Execution process: If there is no exception in the code in the try, then the catch will not automatically. If the code in the try is abnormal, the following code will not be executed, and it will jump directly to the code execution in the catch.
Console.WriteLine("Enter a string of numbers");
try
{
int number = Convert.ToInt32(Console.ReadLine());
}
catch
{
Console.WriteLine("The input content cannot be converted to a number!");
}
Console.WriteLine(number 2);
Console.ReadKey(); In the
above code, Console.WriteLine(number
2); the Number inside will report an error: variable is not assigned, here it involves the scope of the variable.
Variable scope:
The scope of a variable is the range within which you can use this variable.
The scope of a variable generally starts from the parenthesis where it is declared to the ending parenthesis corresponding to that parenthesis.
Within this scope, we can access and use variables. You can't visit beyond this range

//Declare variables outside the try scope so that they can be accessed. There is another problem here. After outputting the code that cannot be converted, it will still output a result of 0, because the following sentence is outside
int number = 0;//Define the variable
Console.WriteLine("input a string of numbers");
try
{
number = Convert.ToInt32(Console.ReadLine());//assignment
}
catch
{
Console.WriteLine("input content, Cannot be converted to numbers!");
}
Console.WriteLine(number * 2);//Use
Console.ReadKey();

The above code will output an extra line of 0 due to errors, so you need to make the following changes to make the input meet certain conditions.
//Declare a bool variable
bool b = true;
//Declare the variable outside the try scope so that it can be accessed. There is another problem here. After outputting the code that cannot be converted, it will still output a result of 0
int number = 0;//Declare a variable
Console.WriteLine("Enter a string of numbers");
try
{
number = Convert.ToInt32(Console.ReadLine());
}
catch
{
Console.WriteLine("The input content cannot be Converted to a number!");
b = false;//If the condition is not met, set bool to false
}
//To execute this code, certain conditions need to be met
//Let the code meet certain conditions before it is executed, use the bool variable
if (b)//Execute only when the bool value is true
{
Console.WriteLine(number * 2);
}
Console.ReadKey();

Second, swicth-case is
used to handle multi-condition fixed value judgment
syntax
switch (variable or expression value)
{
case value 1: code to be executed;
break;
case value 2: code to be executed;
break;
case value 3: The code to be executed;
break;
..........
default: the code to be executed;
break;
}
Execution process: the program executes to the switch, first calculate the value of the variable or expression in the brackets,
and then Hold this value and match with the value behind each case in turn. Once the match is successful,
the code in the case will be executed . After the execution is complete, a break will be encountered. Jump out of the switch-case structure.
If it does not match the value of each case. It depends on whether there is
default in the current switch-case structure . If there is default, the statement in default is executed. If there is no default, the switch-case structure
does nothing.

if-else-if method, this recommendation: multi-condition interval judgment use
bool b = true;
decimal wages = 5000;
Console.WriteLine("input rating AE");//ABCDE mess
string level = Console.ReadLine();
if (level == "A")
{
wages += 500;
}
else if (level == "B")
{
wages += 200;
}
else if (level == "C")
{
}
else if (level == "D")
{
wages -= 200;
}
else if (level == "E")
{
wages -= 500;
}
else
{
Console.WriteLine("Input error, exit the program");
b = false;
}
if (b)
{
Console.WriteLine("Li Silai's annual salary is {0}", wages);
}
Console.ReadKey();

Switch-case method, multi-condition fixed value judgment is recommended
bool b = true;
decimal wages = 5000;
Console.WriteLine("input rating");
string level = Console.ReadLine();
switch (level)
{
case "A": wages += 500;
break;
case "B":wages += 200;
break;
case "C":break;
case "D":wages -= 200;
break;
case "E":wages -= 500;
break;
default:Console.WriteLine("An input error, exit the program!");
b = false;
break;
}
if (b)
{
Console.WriteLine("Li Silai's salary is: {0}", wages);
}
Console .ReadKey();

Comprehensive exercise: Question: According to the score entered by the user, give a rating, >=90 for A, 80B, 70C, 60D, 60 or less E
int score = 0;
Console.WriteLine("Enter an exam score");
try
{
score = Convert.ToInt32(Console.ReadLine());
}
catch
{
Console.WriteLine("Input error, exit the program");
}
switch (score/10)
{
case 10:
case 9:Console.WriteLine("Level A ");
break;
case 8:Console.WriteLine("B-level");
break;
case 7:Console.WriteLine("C-level");
break;
case 6:Console.WriteLine("D-level");
break;
default:Console.WriteLine("Level E");
break;
}
Console.ReadKey();

Comprehensive Exercise 2: The year is required. When entering the month, give the number of days in the month based on the input.
Console.WriteLine("Please enter the year");
try
{
int year = Convert.ToInt32(Console.ReadLine());
Console.WriteLine(" Please enter the month");
try
{
int month = Convert.ToInt32(Console.ReadLine());
if (month >= 1 && month <= 12)
{
int day = 0;
switch (month)
{
case 1:
case 3 :
case 5:
case 7:
case 8:
case 10:
case 12:
day = 31;
break;
case 2:
if ((year% 400 == 0) || (year% 4 == 0 && year% 100 != 0))
{
day = 28;
}
else
{
day = 29;
}
break;
default:
day = 30;
break;
}
Console.WriteLine("{0}year{1} has {2} days in the month", year, month, day);
}//judge whether the month number is normal if ending
else
{
Console.WriteLine ("The entered month is incorrect, exit the program");
}
}//The end of the month try
catch
{
Console.WriteLine("The entered month is incorrect, exit the program");
}
}//The end of the year try
catch
{
Console .WriteLine("Enter the year incorrectly, exit the program!");
}
Console.ReadKey();

3. While loop structure
syntax
while (loop condition)
{
loop body;
}
Execution process: the program runs to while, first determine whether the loop condition in the parentheses of while is established,
if yes, it will return a true , Then execute the loop body, after executing the loop body once, return to the
loop condition to judge again , if it is still true, continue to execute the loop body, if not, then jump out of the while loop.
In a while loop, there is usually a line of code that can change the loop condition so that it will no longer be true one day.
If there is not such a line of code that can change the loop condition, the loop condition will always be true. We call this The cycle
is called an endless loop.
The simplest and most commonly used endless loop:
while(true)
{

}

Features: First judge, then execute, it is possible that the loop will not execute once.

//Print to the console 10 times
//Loop body: console.writeLine("over and over again")
//Loop condition: print 10 times

        //定义一个循环变量来记录循环的次数,每循环一次,变量自增1
        int number = 0;
        while (number < 10)
        {
            Console.WriteLine("一遍又一遍{0}",number);
            number++;//每循环一遍,变量自增1
        }
        Console.ReadKey();

While loop exercises
/
Find the sum of each number from 1-100 to the
loop body 1+2+.....
Loop condition: number <=100
/
int i = 1;
int sum = 0;
while (i <= 100)
{
sum += i;
i++;
}
Console.WriteLine(sum);
Console.ReadKey();

        /*
         求1-100每个偶数加起来的和
         循环体 累加的过程
         循环条件:number <=100
         */
        int i = 1;
        int sum = 0;
        while (i <= 100)
        {
            if (i % 2 == 0)
            {
                sum += i;
            }
                i++;
        }
        Console.WriteLine(sum);
        Console.ReadKey();

        /*
         求1-100每个奇数加起来的和
         循环体 累加的过程
         循环条件:number <=100
         */
        int i = 1;
        int sum = 0;
        while (i <= 100)
        {
            if (i % 2 != 0)
            {
                sum += i;
            }
            i++;
        }
        Console.WriteLine(sum);
        Console.ReadKey();

Fourth, the role of the break keyword
1), you can jump out of the switch-case structure.
2). You can jump out of the current cycle.
Break is generally not used alone, but used together with if judgment, which means that when certain conditions are met, it will no longer loop.

Five Exercises while loop
/
input class size and student achievement once input, calculate grade point average class students and a total score
/
// loop: prompt for student achievement, turn into an integer type, the cumulative total score
// Loop condition: the number of input times is less than or equal to the class number
Console.WriteLine("Please enter the class number!");
int sum = 0;
int i = 1;//Declare a variable to store the number of cycles
int NumberOfPeople = Convert.ToInt32( Console.ReadLine());
while (i<=NumberOfPeople)
{
Console.WriteLine("Please enter the score of {0}!",i);
int score = Convert.ToInt32(Console.ReadLine());
sum += score;//Add each student's score to the total score
i++;
}
Console.WriteLine("The average score is {0}, the total score is {1}", sum / NumberOfPeople, sum);
Console.ReadKey();

/The
teacher asked the students, would you do this question? If the student answers "Yes (y)", then school can be dismissed. If the student answers no (n),
then the teacher is telling it again, asking the students if
1, until they learn, they can leave school
2. Until the student meeting or the teacher speaks Not for 10 times.
The first question after school is my own thought. The reverse is based on the video teacher’s practice
/
string student = "";
while (student != "y")
{
Console.WriteLine("Teacher speaks again And asked: Do you know it?");
student = Console.ReadLine();
}
Console.WriteLine("Okay, you know it, school is over!");
Console.ReadKey();

                                bool b = true;
        int second = 0;
        string student = "";
        while (student != "y")
        {
            if (second != 10)
            {
                Console.WriteLine("老师讲一遍并问道:你会了吗?");
                student = Console.ReadLine();
                second++;
            }
            else
            {
                Console.WriteLine("十遍,老师被气死了!");
                b = false;
                break;
            }
        }
        if (b)
        {
            Console.WriteLine("好的,会了就放学!");
        }
        Console.ReadKey();
                    //反向做法
        string student = "";
        int i = 1;
        while (student != "y" && i <= 10)
        {
            Console.WriteLine("这是老师第{0}几遍讲,你会了吗?", i);
            student = Console.ReadLine();
            if (student == "y")
            {
                Console.WriteLine("会了就放学!");
                break;
            }
            i++;
        }
        Console.ReadKey();

                     /*
         2006年培养学员80000人,每年增长25%,请按照此增长速度,到哪一年培训学员人数达到20万人?PS:这题开始我把判断条件写反了,看了十多分钟才发现问题
         */
        //循坏体:在原基础上,学员每年增长25%累加
        //循环条件:达到20W
        double student = 80000;
        int year = 2006;
        while (student <= 200000)
        {
            Console.WriteLine("现在有{0}人", student);
            student += Convert.ToInt32(student * 0.25);
            Console.WriteLine("经过一年有{0}人", student);
            year++;
        }
        Console.WriteLine("{0}年,人数达到20W", year);
        Console.ReadKey();

                    /*
         提示输入用户名和密码 用户名为admin密码888888
         只要用户名或者密码错误就重新输入
         最多能输入10此
         */

        //循环体,让用户输入用户名和密码
        //10次,或者输对
        int i = 1;
        string useName = "";
        string usePws = "";
        while ((useName != "admin" || usePws != "888888")&&i<=3)
        {
            Console.WriteLine("输入用户名");
            useName = Console.ReadLine();
            Console.WriteLine("输入密码");
            usePws = Console.ReadLine();
            i++;
        }
        Console.ReadKey();

                    2、第二个循环用户B的用户名不能跟A一样,或者为空,
         //循环体:提示用户B输入用户名  接收  判断
         //用户名为空 或者跟A相同
         */
        Console.WriteLine("请输入用户名,不能为空");
        string userNameA = Console.ReadLine();
        while (userNameA == "")
        {
            Console.WriteLine("用户名为空,重新输");
            userNameA = Console.ReadLine();
        }
        Console.WriteLine("请输入用户名,不能为空");
        string userNameB = Console.ReadLine();
        while (userNameB == "" || userNameB == userNameA)
        {
            if (userNameB == "")
            {
                Console.WriteLine("用户名不能为空,重新输入!");
                userNameB = Console.ReadLine();
            }
            else
            {
                Console.WriteLine("用户名重复,重新输入!");
                userNameB = Console.ReadLine();
            }
        }

Six, do-while loop structure
syntax:
do
{
loop body;
}while (loop condition);
execution process: the program will first execute the loop body in do, after the execution is completed, to judge the loop condition of the do-while loop,
if it is established , Then continue to execute the loop body in do, if not established, then jump out of the do-while loop.
Features: loop first, then judge, execute the loop body at least once.

Guess you like

Origin blog.51cto.com/13544652/2576234