2014-10-18 154 views
-1

Soooo这个程序似乎是合乎逻辑的,我已经能够在C++和java中使用相同的想法创建程序,每当我运行它时,所有东西都会突然关闭......也许我只是得到了一些下载错误的东西控制台窗口刚刚关闭? c#

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

namespace ConsoleApplication3 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      /* 
      int[] numbahs= new int[5]; 
      numbahs[0] = 4; 
      numbahs[1] = 3; 
      Console.WriteLine(numbahs[1].ToString()); 

      string[] cow = new string[] { "pee", "poop" }; 
      foreach (string pee in cow) 
      { 

       Console.WriteLine(pee); 
      } 
      */ 

      int x; 
      int y; 
      Console.WriteLine("enter x:"); 
      x = Console.Read(); 
      Console.WriteLine("enter y:"); 
      y = Console.Read(); 
      int z = (x > y)? 8 : 2; 
      Console.WriteLine("x:{0} y:{1} z:{2}",x ,y, z); 
      if (z > x) 
      { 
       Console.WriteLine("yoyo"); 
       Console.Read(); 
      } 
      else { Console.WriteLine("hihi"); } 

      Console.Read(); 

     } 
    } 
} 
+2

的WriteLine( “YOYO” .. “日冰” ......啊......昔日的美好时光:d – 2014-10-18 20:33:50

+3

什么你是否在阻止程序终止?一旦它到达程序结束,它肯定会终止。为什么你期望它不这样做? – 2014-10-18 20:34:00

+0

@DavidHeffernan推测是'Console.Read'。 – 2014-10-18 20:36:07

回答

5

使用到Console.ReadLine

int x; 
    int y; 

    Console.WriteLine("enter x:"); 
    x = int.Parse(Console.ReadLine()); 
    Console.WriteLine("enter y:"); 
    y = int.Parse(Console.ReadLine()); 

    int z = (x > y)? 8 : 2; 

    Console.WriteLine("x:{0} y:{1} z:{2}",x ,y, z); 
    if (z > x) 
    { 
     Console.WriteLine("yoyo"); 
    } 
    else { Console.WriteLine("hihi"); } 

    Console.ReadLine(); 
+0

@ B.K。,实际上这是正确的解决方案,你的不是。 – walther 2014-10-18 20:40:40

+0

@ B.K .:这将起作用。原始代码中的错误是假设Console.Read()会在实际返回输入的下一个字符时读取并返回一个int。输入一些数字和一个换行符会导致所有的'Console.Read()'调用返回并且程序终止。 – 2014-10-18 20:41:44

+0

@ B.K两者都有效。 Console.Readline()会阻塞,直到你键入一个字符串并按下enter键,而console.ReadKey()直到你按任意键。 – 2014-10-18 20:43:51