2017-08-24 3 views
1
using System; 

namespace ConsoleApplication1 
{ 
    class Program 
    {   
     static void Main() 
     {    
      var entry = 0; 
      try { 
       Console.Write("Enter the number of times to print \"Yay!\": "); 
       var entryParsed = int.Parse(Console.ReadLine()); 

       if (entryParsed < 0) 
       { 
        Console.Write("You must enter a positive number."); 
       } 
       else 
       { 
        entry += entryParsed; 
       } 
      } 
      catch (FormatException) 
      { 
       Console.Write("You must enter a whole number."); 
      } 

      var x = 0; 
      while (true) 
      { 
       if (x < entry) 
       { 
        Console.Write("Yay!"); 
        x++; 
       } 
       else 
       { 
        break; 
       } 
      } 
     } 
    } 
} 

最後のコード行では、「var x」とwhileループが何を表しているのか分かりません。このコードサンプルはTreehouseの挑戦からのものですが、 'var x'はプログラムを意図したとおりに動作させる方法を教えてください。ご協力ありがとうございました! :)C# - 最後のwhileループと 'var x'は何をしますか?

+0

それは 'yay'エントリ時間をループする。 forループはより明確になっています – pm100

+1

デバッガを使用してコードをステップ実行すると、コードの内容が正確に表示されます。 –

+1

xはカウンタで、 'Yay'の各印刷後にインクリメントされます。 x = entryの後、whileループのロジックは強制的にそれを強制終了します(ブレーク)。 whileループロジックが少し複雑であることが分かった場合は、代わりに単純なforループを使用することができます。 –

答えて

0

varは、xの型を明示的に定義しないようにする単なる構文上のショートカットです。コンパイラは、割り当てられる値に暗黙のうちにどのタイプがあるかを決定できます。

あなたのループとしては、それはこのように単純化することができます:あなたのコードがより複雑になるにつれて、それはループ内であなたの終了条件があるというリスクを高めているため

var x = 0; 

while (x++ < entry) { 
    Console.Write("Yay!"); 
} 

通常は、明示的なwhile(true)ループを回避します決して満たされず、無限ループに終わってしまいます。出口表現をループ内のどこかに隠すのではなく、はっきりと見えるようにする方が良い方法です。

0

同じことを行うための慣用的な方法は、C#でvarキーワードは「型を推論」という意味

for(int x = 0; x < entry;x++) 
{ 
    Console.Write("Yay!"); 
} 
2

です。

var x = 0; //Means the same thing as latter 
int x = 0; //The compiler actually CONVERTS the former to this in an early pass when it strips away syntactic sugar 

あなたが投稿したコードは非常に初心者を示唆しています。その最後のブロックはforループです。反省して。いずれの選択肢も客観的に劣る。

これを書き換える別の方法があります。確かに陽気な過度な攻撃だが、あなたは考えを得る:

using System; 
using System.Linq; 
using System.Collections.Generic; 

namespace Example 
{ 
    public class Program 
    { 
     public static void Main(string[] args) 
     { 
      int entry = CollectUserInput<int>("Enter the number of times to print \"Yay!\": ", 
       (int x) => x > 0, "Please enter a positive number: "); 

      for (int i=0; i<entry; i++) { 
       Console.Write("Yay!"); 
      } 
     } 

     /// <summary> 
     /// Prompts user for console input; reprompts untils correct type recieved. Returns input as specified type. 
     /// </summary> 
     /// <param name="message">Display message to prompt user for input.</param> 
     private static T CollectUserInput<T>(string message = null) 
     { 
      if (message != null) 
      { 
       Console.WriteLine(message); 
      } 
      while (true) 
      { 
       string rawInput = Console.ReadLine(); 
       try 
       { 
        return (T)Convert.ChangeType(rawInput, typeof(T)); 
       } 
       catch 
       { 
        Console.WriteLine("Please input a response of type: " + typeof(T).ToString()); 
       } 
      } 
     } 

     /// <summary> 
     /// Prompts user for console input; reprompts untils correct type recieved. Returns input as specified type. 
     /// </summary> 
     /// <param name="message">Display message to prompt user for input.</param> 
     /// <param name="validate">Prompt user to reenter input until it passes this validation function.</param> 
     /// <param name="validationFailureMessage">Message displayed to user after each validation failure.</param> 
     private static T CollectUserInput<T>(string message, Func<T, bool> validate, string validationFailureMessage = null) 
     { 
      var input = CollectUserInput<T>(message); 
      bool isValid = validate(input); 
      while (!isValid) 
      { 
       Console.WriteLine(validationFailureMessage); 
       input = CollectUserInput<T>(); 
       isValid = validate(input); 
      } 
      return input; 
     } 
    } 
} 
+0

ああああ、このクレイジーなお尻のコードは私が初心者として理解するのに役立ちますxD –

関連する問題