一个简单的C#程序在执行后给出未处理的异常

时间:2015-06-24 07:06:02

标签: c#

http://i.stack.imgur.com/smnXF.png

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

namespace ConsoleApplication
{
    class Program
    {

        static void Main(string[] args)
        {
            string fname, mname, sname, Desig, input, option1, option2;
            int EmpID;
            option1 = ".value";
            option2 = ".ini";



            Console.WriteLine("Enter Employ ID: \t");                           // Data input start                                                                                                                                                              
            EmpID = Convert.ToInt32(Console.ReadLine());

            Console.WriteLine("\nEnter First Name: \t");
            fname = Console.ReadLine();

            Console.WriteLine("\nEnter Middle Name: \t");
            mname = Console.ReadLine();

            Console.WriteLine("\nEnter Surame: \t");
            sname = Console.ReadLine();

            Console.WriteLine("\nEnter Designation: \t");                       //data input end
            Desig = Console.ReadLine();

            Console.WriteLine("\n\n Choose from the following options:-");                     //options
            Console.WriteLine("\n type .value to show all details of the employees");
            Console.WriteLine("\n type .ini to show all the initials of the employe name");


            input = Console.ReadLine();


            if (String.Equals(input, option1) || String.Equals(input, option2))                 //conditional begin

            {

                 if(string.Equals(input,option1))                                                //sub-conditional begin
            {              
               Console.WriteLine("\n\nName of the employee={1} {2} {3} , His Employee ID ={3} And His Designation is as {4} ",fname[0],mname[0],sname[0],Desig[0]);
            }


            else
            {            
                Console.WriteLine("{1}{2}{3}", fname.Substring(0,1), mname.Substring(0,1), sname.Substring(0,1));
            }
                                                                  //sub-conditional ends

            else
            {            
                Console.WriteLine("\n\nPlease Enter a valid input...");    
            }                                                                                   //conditional ends

        }

    }

}

简单程序,获取输入数据,然后输入选项,检查选项并使用if / else条件运行所需的块。

PS:我知道开关是一个更高贵的选择,但我想知道它有什么问题。

1 个答案:

答案 0 :(得分:2)

该代码应该给FormatException。格式字符串中的索引从零开始,从1开始。在每个Console.WriteLine调用中修复它:

Console.WriteLine("{0}{1}{2}", fname[0], mname[0], sname[0]);