1.3初识c# Console类

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 
 7 namespace HellowWorld
 8 {
 9    /// <summary>
10    /// 该程序实现向控制台输出一条消息
11    /// </summary>
12    /// <param name="args"></param>
13    class Program
14    {
15       //程序的入口
16       static void Main(string[] args)
17       {
18          /*从这里开始编写代码*/
19          //法一
20          Console.WriteLine();
21          //法二
22          Console.WriteLine("hellow world");//向控制台输出一句话
23          int a = 0;
24          Console.WriteLine(a);//输出变量
25          //法三
26          string str0 = "world";
27          string str1 = "!";
28          Console.WriteLine("hello \n{0}\t{1}", str0,str1);
29          Console.ReadLine();//使输出显示暂停
30       }
31    }
32 }
View Code

1.其中的Console是c#中的控制台类,利用它我们可以轻松实现控制台的输入输出。
常用的输出方法有两个:Console.WriteLine()和Console.Write(),其唯一区别就是前者在输出后换行,后者输出后不换行,

常用的输入方法:Console.ReadLine(),这句的作用就是时输出窗口弹出后停在那里等待用户输入然后再关闭,若去掉该句代码,输出窗口一闪而逝。

调用Console.WriteLine()的方式常用的有以上三种,法一,法二与java中的System.out.println()相同第三种方法是Console.WriteLine("格式字符串","变量列表"),hello {0}就是格式字符串,{0}叫做占位符,它占的就是变量str的位置,在格式字符串中我们依次使用{0},{1},{2}......代表要输出的变量,然后将变量依次排列在变量列表中,0对应列表的第1个变量,1对应列表的第2个变量,依此类推。

注:在格式字符串中也可以使用\n(换行),\t(制表)来控制输出,如图运行结果

 2.与Console.WriteLine()对应从控制台输入可以使用Console.ReadLine(),Console.ReadLine()返回一个字符串,可将其赋给一个变量,若变量是整形的可使用 int a=int.Parse(Console.ReadLine());

示例如下

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 
 7 namespace HellowWorld
 8 {
 9    /// <summary>
10    /// 该程序实现向控制台输出一条消息
11    /// </summary>
12    /// <param name="args"></param>
13    class Program
14    {
15       //程序的入口
16       static void Main(string[] args)
17       {
18          string name1;
19          string name2;
20          int age1;
21          int age2;
22          //输入第一个学生信息
23          string info1 = "please input the first student's name:";
24          Console.WriteLine(info1);
25          name1 = Console.ReadLine();
26          info1 = info1.Replace("name", "old");
27          Console.WriteLine(info1);
28          age1 = int.Parse(Console.ReadLine());
29          //输入第二个学生信息
30          info1 = info1.Replace("first", "second").Replace("old", "name");
31          Console.WriteLine(info1);
32          name2 = Console.ReadLine();
33          info1 = info1.Replace("name", "old");
34          Console.WriteLine(info1);
35          age2 = int.Parse(Console.ReadLine());
36          //输出学员信息
37          Console.WriteLine("the first student's name is " + name1 + " and he is "+ age1 + " years old");
38          Console.WriteLine("the first student's name is {0} and he is {1} years old", name2, age2);
39          Console.ReadLine();
40       }
41    }
42 }
View Code

运行结果如图

注:教你一招快速输入Console.WriteLine()方法cw+tab+tab

posted @ 2017-05-25 11:16  LJLLY  阅读(1084)  评论(0编辑  收藏  举报