2010-02-03 5 views
1

파일에서 숫자를 함수에서 전달 된 숫자와 비교하는 방법을 알지 못합니다. 나는 파일이 얼마나 아무 생각이추측 게임 및 번호 비교

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.IO; 

namespace Guess_Game 
{ 
    class Program 
    { 
    static void Main(string[] args) 
    { 
     int quantity; 
     int min, max; 
     Console.WriteLine("Enter the Quantity of Numbers : "); 
     quantity = int.Parse(Console.ReadLine()); 

     Console.WriteLine("Enter the Maximum and Minimum Number that you wish to be in your file : \n"); 
     Console.WriteLine("MIN : "); 
     min = int.Parse(Console.ReadLine()); 
     Console.WriteLine("MAX : "); 
     max = int.Parse(Console.ReadLine()); 
     Console.WriteLine("Now, Guess the Number : "); 
     int number = int.Parse(Console.ReadLine()); 

     Console.WriteLine("Now Guess a Number That already contains in a File : "); 
     number = int.Parse(Console.ReadLine()); 
     GuessGame(min, max, quantity, number); 

     //if(number!= // number not equal to that number that contains in a file.. how to write it in that 
      //if condition.. 
    } 

    static void GuessGame(int min,int max,int quantity,int number) 
    { 
     Random r = new Random(); 
     StreamWriter sw = new StreamWriter(@"D:\nasir\Guess Game\Guess Game\bin\Debug\ Guess Game.txt"); 

     for (int i = 0; i < quantity; i++) 
     { 
      int temp = r.Next(min, max); 
      sw.WriteLine(temp); 
     } 
     // while(number != sw.WriteLine()) 
     { 
      Console.WriteLine("Your Guess is Wrong!"); 
     } 
     sw.Close(); 
    } 
    } 
} 
+3

분 = INT를 즐길 향상 선물로 compareson

을 : 당신이 당신의 추측이 파일 리더를 추가 입력 한 후 그렇게 fristly 연결을 닫습니다 .Parse (Console.ReadLine()); 내가 "A"를 입력하면 폭발합니다 :) - 항상 tryparse를 사용하고, 사용자를 믿지 마십시오! – balexandre

+0

differnce B/W 구문 분석을 이해하고 구문 분석을 시도하지 않습니다. 파스는 모든 숫자를 변환 할 수있는 숫자를 변환합니다 ..하지만 구문 분석을 시도합니까 .. u는 plx를 설명 할 수 있습니까? – Abid

+1

TryParse 메서드를 사용하여 문자열을 int로 안전하게 구문 분석 할 수 있습니다.나는 그것이 예외를 던지지는 않는다는 것을 의미하지만 성공하고 값이 out 매개 변수로 반환되면 부울을 반환합니다. 문자열 값이 정수가 아니어도 프로그램이 계속 작동 할 수 있지만 허용되지 않는 경우 Parse를 사용하는 것이 좋습니다. – Beatles1692

답변

0

입니다 ...

이미지 :

12 
17 
9 

당신이 사용

내 코드입니다

string[] fileNumbers = File.ReadAllLines("C:\MyGuessNumbers.txt"); 

그래서 file에 숫자가 모두옵니다. Console.ReadLine()가 정수는하지 않습니다 경우

int quantity; 
Console.WriteLine("Enter the Quantity of Numbers : "); 
quantity = int.Parse(Console.ReadLine()); 

: 문자열 배열, 단지 루프에 엄버 및 사용자 코드에서 PARSE

대 :

TRY 구문 분석 비교 객체가 구문 분석 할 수 없다는 예외가, 마녀는

,691를 사용하는 경우 "A"는 문자열이 아닌 정수

이다, 쓰기입니다

int quantity = 0; 
Console.WriteLine("Enter the Quantity of Numbers : "); 
while(! int.TryParse(Console.ReadLine(), out quantity)) 
    Console.WriteLine("That does not seam to be an integer, please only use numbers!\nEnter the Quantity of Numbers : "); 

TRY를 구문 분석 할 때 TRY를 반환하거나 정수를 성공적으로 구문 분석 한 경우 FALSE를 반환하므로 숫자 인 경우 유효성을 검사합니다.

이 예제에서 TryParse가 false를 반환하는 동안 사용자가 프로그래밍 언어로 숫자를 입력 할 때까지 루프됩니다.

+0

예. u로 내 프로그램에서, 나는 임의의 숫자를 생성했습니다. .. 내 .txt 파일 확장자에 저장됩니다. – Abid

+1

프로그램에 이미 숫자가있는 경우 왜 코드의 다음 줄에 파일로 채우고 있습니까? 그 파일 ??? 모든 난수를 반환하고 아니오를 비교하는 것이 훨씬 빠릅니까? – balexandre

+0

당신의 이해를 위해 TRY PARSE 대 PARSE를 추가했습니다 ... – balexandre

2

매번 (불공정 한 IMO) 주사위를 던지고 그 파일을 읽지 않고 그냥 씁니다. 이제이 시작하자 :

static void Main() 
{ 
    Random r = new Random(); 
    bool lucky = false; 
    int maxTries, minValue, maxValue, guess = 0; 

    GetInput("Enter number of tries: ", out maxTries); 
    GetInput("Enter minimum number : ", out minValue); 
    GetInput("Enter maximum number : ", out maxValue); 

    int magical = r.Next(minValue, maxValue); // only once 
    for (int i = 1; i <= maxTries; i++) 
    { 
     GetInput("Enter your guess : ", out guess); 
     if (guess == magical) 
     { 
      lucky = true; 
      break; 
     } 
    } 

    Console.WriteLine("you.Lucky = {0};", lucky); 
    Console.ReadLine(); 
} 

static void GetInput(string text, out int variable) 
{ 
    do Console.Write(text);   // avoiding stackoverflow.com scroll 
    while (!Int32.TryParse(Console.ReadLine(), out variable)); 
} 

을 당신이 파일에서 번호를 얻을 같은 것을 시도하려는 경우

List<int> magicals = new List<int>(); 
using (StreamReader reader = new StreamReader("GuessGame.txt")) 
{ 
    int magical = 0; 
    string line = ""; 
    while (!String.IsNullOrEmpty(line = reader.ReadLine())) 
    { 
     if (Int32.TryParse(line, out magical)) 
      magicals.Add(magical); 
    } 
} 

및 시험은 다음과 같이이다 :

if(magicals.Contains(guess)) 
+1

나는 이것이 일종의 숙제라고 생각한다. 전체 해결책을 보여 주거나 선물하는 것이 좋지 않다. 발레? :) – balexandre

+0

@balexandre는 나를 위해 숙제로 보이지 않지만 당신의 요점을 이해했습니다. curintia :) –

+0

그럼 실제 문제를 해결하고 있다고 생각하니? –

0

당신이이 작은 실수는 정수를 파일 작성자 sw과 비교하므로 추측은 항상 잘못된 것입니다.

sw.Close();  
StreamReader sr = new StreamReader(@"C:Guess Game.txt"); 

그때 내가 당신의 홀 코드가

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.IO; 

namespace Guess_Game 
{ 
class Program 
{ 
    static void Main(string[] args) 
    { 
     int quantity; 
     int min, max; 
     int[] number = new int[10]; 
     Console.WriteLine("Enter the Quantity of Numbers : "); 
     quantity = int.Parse(Console.ReadLine()); 

     Console.WriteLine("Enter the Maximum and Minimum Number t \n"); 
     Console.WriteLine("MIN : "); 
     min = int.Parse(Console.ReadLine()); 
     Console.WriteLine("MAX : "); 
     max = int.Parse(Console.ReadLine()); 
     for (int i = 0; i < quantity; i++) 
     { 
      Console.WriteLine("Now, Guess the {0}Number : ", i + 1); 
      number[i] = int.Parse(Console.ReadLine()); 
     } 

     GuessGame(min, max, quantity, number); 

     //if(number!= // number not equal to that number that contains in a file.. how to write it in that 
     //if condition.. 
    } 

    static void GuessGame(int min, int max, int quantity, int[] number) 
    { 
     Random r = new Random(); 
     StreamWriter sw = new StreamWriter(@"C: Guess Game.txt"); 

     int[] temp = new int[quantity]; 
     for (int i = 0; i < quantity; i++) 
     { 
      temp[i] = r.Next(min, max); 
      sw.WriteLine(temp[i]); 

     } 
     sw.Close(); 
     StreamReader sr = new StreamReader(@"C: Guess Game.txt"); 
     int trying = 3; 
     int[] guess = new int[10]; 
     for (int i = 0; i <= quantity; i++) 
      guess[i] = Convert.ToInt32(sr.ReadLine()); 

     for (int i = 0; i < quantity;i++) 
      for (int j = 0; j < quantity; j++) 
       if (number[j] != guess[i]) 
       { 


     System.Console.WriteLine("you have wrong Answer,you have {0} try ", trying--); 
        for (int k = 0; k < quantity; k++) 
        { 
         Console.WriteLine("you {0} Number is", k+1); 
         number[k] = Convert.ToInt32(System.Console.ReadLine()); 
        } 

        if(trying==0) 

        for (j = 0; j <quantity; j++) 
      Console.WriteLine("Your Guess is right! the right answer is{0} ", guess[j]); 




       } 

     for (int j = 0; j < quantity; j++) 
     Console.WriteLine("Your Guess is right! the right answer is{0} ", guess[j]); 

    Console.ReadLine(); } 
} 
} 
+0

내 대답을 편집 –

+0

죄송 합니다만 지금 편집하면 의견이 맞다면 mseeage를 제공합니다. –