C# 學習 16 循環與跳轉

迭代(循環)語句 && 跳轉語句

  1. while
    在這裏插入圖片描述

  2. do while
    和While類似

    continue與break的區別,看下面的例子

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

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            int score = 0;
            bool canContinue = true;
            do
            {
                int x;
                Console.WriteLine("Please input first number");
                string str1 = Console.ReadLine();
                if (str1.ToLower() == "end")
                {
                    break;
                }
                try
                {
                     x = int.Parse(str1);

                }
                catch
                {
                    Console.WriteLine("Re Input");
                    continue;
               
                }

                Console.WriteLine("Please input second number");
                string str2 = Console.ReadLine();
                if (str2.ToLower() == "end")
                {
                    break;
                }
                int y;
                try
                {
                    y = int.Parse(str2);
                }
                catch 
                {

                    Console.WriteLine("Re Input ");
                    continue;
                }
                

                int sum = x + y;
                if (sum==100)
                {
                    score++;
                    Console.WriteLine("Correct{0}+{1}={2}",x,y,sum);
                }
                else
                 {
                    Console.WriteLine("Error{0}+{1}={2}",x,y,sum);
                    canContinue = false;
                }

            }while (canContinue) ;
            Console.WriteLine("Your Score is {0}",score);
            Console.WriteLine("Game Over");
        }
    }
}

  1. for
    在這裏插入圖片描述
  2. foreach
    集合遍歷循環,枚舉一個集合中的元素

什麼樣的集合可以被枚舉,帶有IEnumerable的類
在這裏插入圖片描述

什麼是迭代器。
指月,

在這裏插入圖片描述

return

原則:儘早return

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章