C#语句控制 判断语句、case里面的goto语句、foreach语句

本文详细介绍了C#中的if判断语句、如何在case语句中使用goto进行流程跳转,以及foreach语句的使用方法,包括示例代码和实际应用演示。

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

if判断语句:

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

namespace wm110_2
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("输入任意的一个数字、字母:\nx=");  //提示
            char x = Convert.ToChar(Console.ReadLine());   //用来保存输入的字符
            if (Char.IsUpper(x))
            {
                Console.WriteLine("大写字母");
            }
            else if (Char.IsLower(x))
            {
                Console.WriteLine("小写字母");
            }
            else if (Char.IsDigit(x))
            {
                Console.WriteLine("数字");
            }
            else 
            {
                Console.WriteLine("未知");
            }
        }
    }
}
运行结果:

输入任意的一个数字、字母:
x=&
未知
请按任意键继续. . .

在case语句里面使用goto:

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

namespace wm110_3
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("输出结果为:\n选对号码:1=小  2=大  3=很大");
            Console.Write("请输入你的选择:");
            string s = Console.ReadLine();
            int n = int.Parse(s);        //将字符串转化为整形
            int cost = 0;
            switch (n)
            {
                case 1:
                    cost += 25;
                    break;
                case 2:
                    cost += 25;
                    goto case 1;
                case 3:
                    cost += 50;
                    goto case 1;
                default:
                    Console.WriteLine("请安要求输入!!!");
                    break;
            }
            if (cost != 0)
            {
                Console.WriteLine("应付费用{0}元",cost);
            }
        }
    }
}

运行结果:

输出结果为:
选对号码:1=小  2=大  3=很大
请输入你的选择:3
应付费用75元
请按任意键继续. . .


foreach语句的使用:

foreach语句是为了简化对数组或集合的循环访问而设计的。

格式如下:

foreach(类型 变量名 in 集合对象)

{

        //语句体

}

示例:利用foreach输出一个数组里面的全部内容

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

namespace wm110_4
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] Array = { 0, 2, 4, 6, 8, 10 };    //初始化一个整形数组
            Console.WriteLine("输出数组里面的每一个元素:");
            foreach (int temp in Array)
            {
                Console.Write(temp.ToString() + "  ");  //输出数组中每一个元素的值
            }
            Console.WriteLine();
        }
    }
}

运行结果:

输出数组里面的每一个元素:
0  2  4  6  8  10
请按任意键继续. . .


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值