如何询问用户输入

时间:2015-07-20 20:52:59

标签: c#

我想知道如何询问用户输入,然后检查输入的某些属性,并显示除逗号以外的逗号分隔的输出。这是我到目前为止所拥有的。我正在努力要求用户输入,并在输出结束时删除逗号:

using System;
class TestClass
{
 static void Main(string[] args)
 {

 int x = Convert.ToInt32(Console.ReadLine());
 if (x < 0 || x > 25)
   Console.WriteLine("sorry, that number is invalid");

 else
   while (x <= 30)
   {  
     if(x <= 30)
       Console.Write(string.Join(",", x));
       Console.Write(", ");

       x = x + 1;
   }
 }
}

2 个答案:

答案 0 :(得分:0)

将循环更改为

while (x <= 30) {  
    Console.Write(x);
    if (x < 30) { // Execute for all except for x == 30
        Console.Write(", ");
    }
    x++;
}

String.Join用于连接数组的项目。这不是你想要的。

您也可以使用StringBuilder。它允许删除最后一个", "

var sb = new StringBuilder();
while (x <= 30) {  
    sb.Append(x).Append(", ");
    x++;
}
sb.Length -= 2;  // Remove the 2 last characters ", "
Console.WriteLine(sb);

答案 1 :(得分:0)

目前尚不清楚您要完成的任务。也许是这样的?

void Main()
{
  int x;
  List<int> numbers = new List<int>();

  while (true)
  {
     Console.WriteLine ("Enter a whole number between 1 and 25 or 0 to end:");
     string input = Console.ReadLine();

     bool isInteger = int.TryParse(input, out x);

     if (!isInteger || x < 0 || x > 25)
     {
        Console.WriteLine (@"Didn't I tell you ""Enter a whole number between 1 and 25 or 0 to end? Try again""");
        continue;
     }

     if (x == 0)
     {
       if (numbers.Count () == 0)
       {
        Console.WriteLine ("Pity you quit the game too early.");
       }
       else
       {
        Console.WriteLine (@"You have entered {0} numbers. The  numbers you entered were:[{1}]
Their sum is:{2} 
and their average is:{3}", 
           numbers.Count, 
           string.Join(",", numbers.Select (n => n.ToString())), 
           numbers.Sum(), 
           numbers.Average ());
       }
       break;
     }
     else
     {
       numbers.Add(x);
     }
   }
}