한빛아카데미의 C# 프로그래밍 책 247쪽 문제를 참고했고, 정수에 한하여 무한히 입력받고, 정수 외의 입력값은 프로그램 종료임.

문제에선 요구한 것이 아니지만, 정답을 미리 알려주는 것과 간단한 예외처리를 추가함(정수 외의 엉뚱한 값 넣으면 종료).


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42

using
 System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using
 System.Threading.Tasks;
 
namespace GuessNum
{
    class Program
    {
        static void Main(string[] args)
        {
            Random randint = new Random();
            int i = (int)Math.Round(randint.NextDouble() * 10000);
            Console.WriteLine("정답: {0}", i); // 정답
            
            try            
            {
                while (true)
                {    
                    Console.Write("숫자를 입력하세요?");
                    string inputStr = Console.ReadLine();
                    int inputNum = Int32.Parse(inputStr);
 
                    if (inputNum == i)                  
                    {           
                        Console.WriteLine("정답입니다.");          
                        break;              
                    }              
                    else                 
                    {                     
                        Console.WriteLine("틀렸습니다.");          
                    }           
                }         
            }    
            catch (System.FormatException)    
            {       
             Console.WriteLine("정수가 아닌 입력값으로 인하여 프로그램을 종료합니다.");   
             // Console.WriteLine(exception.GetType());       
            }   
        } 
    }
}
cs