2016-11-05 9 views
-2

このプログラムはうまくいきません。出力は常に: アルコールを飲むことができます!C#ifとconsoleが正常に動作しない

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

namespace Superif 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      int age; 
      string result; 

      Console.WriteLine("Please enter your age!"); 
      age = Console.Read(); 

      if (age >= 18) 
      { 
       result = "You can drink alcohol!"; 
      } 
      else 
      { 
       result = "You can't drink alcohol!"; 
      } 


      Console.WriteLine(result); 
      Console.ReadKey(); 

     } 
    } 
} 
+2

これは 'if'文がうまく動作しないこととは関係ありません。私はあなたが 'age'の価値をプリントアウトすることをお勧めします...私はそれがあなたが期待するものではないと確信しています。 –

答えて

4

あなたは間違った方法を使用しています。 Console.ReadMDSN

は、標準入力ストリームから次の文字を読み込みます。

インスタンス入力"18"ageの値をチェックするためにあなたはそれが"1"のASCII値をある49を持って表示されます。文字列全体のラインを読み込み、intにそれを解析

使用Console.ReadLine()代わりに:も

static void Main(string[] args) 
{ 
    int age; 
    string result; 

    Console.WriteLine("Please enter your age!"); 
    if(!int.TryParse(Console.ReadLine(),out age)) 
    { 
     result = "Invalid Input"; 
    } 
    else if (age >= 18) 
    { 
     result = "You can drink alcohol!"; 
    } 
    else 
    { 
     result = "You can't drink alcohol!"; 
    } 

    Console.WriteLine(result); 
    Console.ReadKey(); 
} 

は、私は、無効なキャストの例外を回避するためにint.TryParseではなくint.Parseを使用することを決めたことに気づく

+1

投稿されましたが、あなたは最初です:)。 – Berkay

3

Console.Read()は整数値ではないASCII値を与えます。だからConsole.ReadLine()を試してみてください。

int age; 
    string result; 

    Console.WriteLine("Please enter your age!"); 
    age = Convert.ToInt32(Console.ReadLine()); 

    if (age >= 18) 
    { 
     result = "You can drink alcohol!"; 
    } 
    else 
    { 
     result = "You can't drink alcohol!"; 
    } 


    Console.WriteLine(result); 
    Console.ReadKey(); 
関連する問題