2013-11-28 41 views
3
string FirstName = Console.ReadLine(); 
      if (FirstName.Length > 12) 
      { 
       Console.WriteLine("......................................."); 
      } 
      if(FirstName.Length<3) 
      { 
       Console.WriteLine("...................."); 
      } 
      Console.WriteLine("..................."); 
      string SecondName = Console.ReadLine(); 
      if (SecondName.Length > 12) 
      { 
       Console.WriteLine("............................."); 
      } 
      if(SecondName.Length<3) 
      { 

我想要停止程序,如果他们按下输入没有提及价值,怎么做?? /?如何停止在C#中进一步执行程序#

+0

可能重复的[如何关闭一个无形的C#应用​​程序](http://stackoverflow.com/questions/181018/how-to-close-a-formless-c-sharp-application) –

+1

这个问题和你的其他问题表明你对C#完全陌生。请先阅读一些教程。 – venerik

+0

阅读更多的答案在这里:http://stackoverflow.com/a/4898117/468718 –

回答

2

我想你想有一个非空字符串值从控制台输入,如果输入为空,则希望终止应用程序。使用以下代码:

Console.WriteLine("Enter a value: "); 
string str = Console.ReadLine(); 
//If pressed enter here without a value or data, how to stop the program here without 
//further execution?? 
if (string.IsNullOrWhiteSpace(str)) 
    return; 
else 
{ 
    Console.WriteLine(string.Format("you have entered: '{0}'", str)); 
    Console.Read(); 
} 

如果用户将输入任何类型的空字符串或空格,应用程序将在他/她按回车键时终止。

2

Console.ReadLine()返回一个字符串。如果没有输入任何内容,而人类只是按下回车键,我们会得到一个空字符串。

有很多方法可以测试一个字符串是否为“空”,以表示空的各种定义。空以及如何一些常见的定义来测试他们:

  • null和不包含数据:myString.Length == 0
  • null或不包含数据:string.IsNullOrEmpty(myString)
  • null,空,或只是空白:string.IsNullOrWhiteSpace(myString)

Environment.Exit()将以您指定的退出代码结束该过程。

将以上测试之一与Environment.Exit()(可能是if)合并,您可以在没有“值或数据”时停止该过程。

另请注意,从Main返回是退出该过程的另一种方式。

6
string key = Console.ReadKey().ToString(); //Read what is being pressed 
if(key == "") { 
    Console.WriteLine("User pressed enter!"); 
    return; //stop further execution 
} 
+0

我的意思是如果“输入”没有任何价值的按下, 如果他们在输入值后按Enter键 – Shalya

+0

我的意思是说只有当“输入“被按下没有任何价值,如果他们把一个值并按下输入怎么办? – Shalya

+0

@ user2996625如果添加一些值,上面的if语句将不会被执行。即使你输入了一些值,你想停止吗? – Praveen

相关问题