2013-01-02 44 views
0

問題是我必須做一個控制檯應用程序,我輸入一個數字,它寫出符號「|」儘可能多的我插入。例如,如果我插入數字6它寫出||||||。它一直詢問,直到我插入0並關閉。到目前爲止,輸入是這樣的:輸入字符

int input; 

Console.Write("\n\n Insert an number ---> "); 
input = Convert.ToInt32(Console.ReadLine()); 

我已經嘗試使用char數組,但沒有用。

+3

那麼,你用char數組方法得到了多少?你的代碼是什麼樣的?目前,這聽起來像是你想讓我們爲你做你的功課... –

+3

你讀過「循環」一章嗎? – I4V

+0

我可能會用循環 –

回答

3

實際上有a constructorstring初始化字符串給定的字符一定次數:

string s = new string('|', 10);

s將字符串"||||||||||"

2

循環是那麼2012 :)

using System; 
using System.Linq; 

internal class Program 
{ 
    private static void Main(string[] args) 
    { 
    Enumerable.Range(0, Int32.MaxValue) 
     .Select(i => Int32.TryParse(Console.ReadLine(), out i) ? i : -1) 
     .Where(i => i >= 0) 
     .TakeWhile(i => i > 0) 
     .Select(i => { 
     Console.WriteLine(String.Join("", Enumerable.Repeat("|", i))); 
     return 0;}) 
     .Count(); 
    } 
} 

描述(即使答案是非常不嚴肅):

  • Enumerable.Range是讓半無限(克里斯·辛克萊指出,這只是2,147,483,647次)枚舉有大部分單個語句的代碼。
  • 第一個Select逐行讀取輸入並將有效輸入轉換爲整數,其餘爲-1(請注意,在此示例中-1是「無效輸入」的可能值,通常會返回Tuple<int, bool>int?來表示無效值
  • Where過濾掉「無效」的輸入(輸入正確負數以及所有非數字,其中爲-1通過以前報道Select)。
  • TakeWhile提供終止條件爲0
  • Select打印結果。請注意,要從相同字符的多個副本構造字符串應該使用適當的new String("|", count)構造函數,但它不那麼有趣。
  • finally Count強制立即重複查詢。
+0

嘗試爲該readline實現TryParse :-P – Fredou

+0

但是,這隻會運行2,147,483,647次! –

+3

-1,程序只是在進行任何輸入之前競爭 –

0

僞代碼

is read line a number 
    until read line is 0 
     for 1 to the number 
      print | 
    is read line a number 
    if not a number go back at asking the number saying it is not a number 
if not a number go back at asking the number saying it is not a number 

現在有樂趣做作業

0

拖基本概念,你應該知道

for循環:

for(int i=0; i<input; i++) 
{ 
    // do stuff 
} 

這是做某事的常見模式input次,所以如果input等於6,那麼它會比//do stuff大6倍。


控制檯。寫

Console.Write('|'); 

Console.Write寫入文本控制檯沒有將在末處加入一個新行。


我確定您可以將某些語言功能以某種方式組合起來,以滿足您的要求。

+0

非常感謝。我用它並使用Do While循環。 :) –