2017-06-28 27 views
-4
public class call 
{ 
    DateTime time = DateTime.Now; 
    public void check() 
    { 
     int count=0; 
     if(time < time.AddSeconds(30)) 
     { 
      count ++; 
      if(count == 5) 
      { 
       Console.WriteLine(count); 
      } 
     } 
public class Program 
{ 
    public static void Main(string[] args) 
    { 
     int input; 
     string sinput; 
     call one = new call(); 
     call two = new call(); 

     sinput = Console.ReadLine(); 
     input = int.Parse(sinput); 

     do{ 
      switch(input) 
      case 1: one.check(); 
      break; 
      case 2: two.check(); 
      break; 
      default: Console.WriteLine(":::"); 
      break; 
     }while(input > 9) 
    } 
} 
} 

我是新來的編程...我給輸入1至9 ..如果發生相同的輸入5次在30秒我要打印

我試圖打印如果數量發生在30秒內5次...... 我給輸入1至9 ..如果發生相同的輸入5次在30秒我想打印的..

+0

請提供可編譯代碼 - 它是Java還是C#? –

+0

我不知道如何爲對象創建做時間常量 – user8223535

+0

@ user8223535爲什麼Java標籤呢? – shole

回答

0

你有幾個錯誤:

您可能需要更換:

if(time < time.AddSeconds(30)) 

用的東西比較當前的時間,例如:

if(DateTime.Now < time.AddSeconds(30)) 

你也在你的檢查方法遞增兩次計數,不知道這是故意的。

裏面的DO循環的開關本體必須的{}內,你應該每次都讀一個新的輸入或做別的事情改變輸入或你的循環將永遠運行下去。

你也應該始終驗證用戶輸入。在這種情況下,如果有人進入其他的東西多了一些應用程序會崩潰形成這樣的代碼:

sinput = Console.ReadLine(); 
input = int.Parse(sinput); 

而是查找該int.TryParse方法。

+0

問題是,當我再次給輸入1的時間改變到當前時間...但我不想那樣..我需要同樣的時間,如果它不存在30秒相同的輸入 – user8223535

+0

我的第二個代碼被阻止解決這個問題問題。 「如果(DateTime.Now

+0

你能給出更好的邏輯,用於該程序... – user8223535

0

創建類似的東西記錄在一定的輸入值的數據(即,存儲在它們進入的日期),並結合這些類的類。像,在僞碼:

class SingleInputLogger { 

    List<Date> dates 

    void addDate(Date date){ 
     push date in dates 
    } 

    unsigned int currentSize(){ 
     remove all entries from dates which are too old 
     return size of dates 
    } 
} 

class InputLogger { 

    Array<SingleInputLogger> singleInputLoggers of size 10 (or 9 if only 1..9, but then mind the offset) 

    //adds an input and also returns true if the input has a count of more than five 
    void addInput(int input){ 
     singleInputLoggers[input].addDate(currentTime()) 

    } 

    bool checkInput(int input){ 
     if(singleInputLoggers[input].currentSize() >= 5){ 
      return true 
     } 
     return false 
    } 

然後,主例程變得

InputLogger logger 

while(get input){ 
    logger.addInput(input) 
    if(logger.checkInput(input)){ 
     display message "input " + input + " was entered more than five times in 30s" 
    } 
} 

(使用列表,以指示一個鏈表,以便能夠有效地除去前面的條目,陣列被用於表明靜態大小的快速訪問的結構)

記得讓這樣的類你做的工作。儘量使用盡可能少的功能,而採用方法。

如果有人有這些類的(我承認我的名字是不是很大)更好的名字,隨意編輯我的答案。

+0

我有addinput方法的混亂...該代碼singleInpuLoggers [輸入]將顯示錯誤 – user8223535

+0

@ user8223535我不知道你的實現。用一個實現發佈類似cpp.sh的鏈接。陣列的尺寸是否正確? – Aziuth

相關問題