2014-02-21 2 views
0

Newb/hobbiest 여기서 배열에 대한 나의 이해를 높이려고 노력 중이며 그 목적으로 약간의 식사 계산기를 만들려고합니다. 3 개의 문자열과 하나의 double (사용자 성, 사용자 성, Resturant의 이름, 식사 비용 인 DOUBLE)을 보유 할 배열에 사용자 데이터를 저장합니다. 나는 이것을하기 위해 노력하는 방법보다 훨씬 쉬운 방법이 있다는 것을 알고있다. 그러나 나의 목적은 루프와 메소드를 이해하기 시작하면서 배열이 어떻게 작동하는지 이해하는 것이다. 어레이의 무서워 그래서 나는 오늘 밤에 시작하는 모든 주말 긴 배열과 함께 일하도록 강요합니다 - 긴 주말 그리고 나는 그것이 학습의 가치있는 주말이 되길 바랍니다 : D)배열 A에서 질문하고 배열 b에 해당 답변을 저장하는 방법

현재 배열을 채우는 방법을 연구 중입니다. GetUserData (질문하는 질문) 호출; GetUserData는 사용자에게 특정 유형의 데이터 (마지막 위치 [3]이 아니면 나중에 수학 할 두 자리가 아닌 문자열)를 묻습니다. GetUserData 루프가 arrQuestions []를 호출하여 사용자 질문을합니다. GetUserData는 사용자 응답을 해당하는 arrUserData의 위치 [ arrUserData []가 채워집니다. (이 시점에서 4 개의 문자열이 있으면 가능한 한 수학을 수행 할 때 4 개의 문자열을 변환해야합니다.)

요약하면 , 한 배열의 질문을 일련의 질문을하고 다른 배열을 저장하는 메서드를 만들려고 노력하고있어 그 배열의 더 나은 이해를 얻으려고 어떻게 모든 종류의 이상한 일을 할 수 있습니다. 그 (것)들을 사용하고, 그들이 무엇을 위해 좋으며, 무엇이 좋지 않은지를 알아야합니다.

그리고 나는 이미 Google에이 문제에 대한 답변을 시도 했으므로 약속드립니다. http://msdn.microsoft.com/en-us/library/ttw7t8t6.aspx 및 stackOverflow를 포함하여 여러 곳에서 배열을 읽었지만 찾은 답변은 다음과 같이 작성되지 않았습니다. 나의 기술 수준의 누군가 이해/나의 이해가 내가 지금까지 읽을 수 있었던 것에서 대답을 거룩하게 할 수는 없다.

다음 코드는 모두 내가 당신이 보여준 기존의 지식의 일부를 사용 생각하는 무언가를 추천하려고합니다 코드보고에서 '프로그램'클래스

public void Play() 
{ 
    GetString("+ + + Meal Calculator Exercise + + +"); 

    String command = ""; 

    String[] arrQuestions = new String[3];//questions asked 
    arrQuestions [0] = "First Name: ";//string back 
    arrQuestions [1] = "Last Name: ";//string back 
    arrQuestions [2] = "Restaurant Name: ";//string back 
    arrQuestions [3] = "Cost of Meal: ";//I want a double back for this question 


    String[] arrUserData = new String[3];/user answers stored 
    arrUserData[0] = " ";//string 
    arrUserData[1] = " ";//string 
    arrUserData[2] = " ";//string 
    arrUserData[3] = " ";//figure out how to convert to double 


    do { 
     GetString("+ + + Meal Calculator Exercise + + +"); 

     GetUserData(arrQuestions[i]);//run loop, ask questions populate arrUserData array 

     GetString("Again? "); 
     command = Console.ReadLine().ToLower().Trim(); 
     Console.Clear(); 
    } 

    while (command == "y" || command == "yes"); 

    GetString("+ + + Thank you + + + Have a wonderful time + + + Goodbye! + + +");   
} 

public String GetString(String strTxt) { 
    Console.WriteLine(strTxt);return Console.ReadLine();} 

public Array GetUserData(String strTxt) 
{ 
    for (int i = 0; i < arrUserData.Length; i++) 
    Console.WriteLine(arrQuestion[i]); 
    return Console.ReadLine(arrUserData[i]); 
} 


static void Main(string[] args){ 
    Program myProgram = new Program(); 
    myProgram.Play();} 
+0

이 포럼 사이트와 달리, 우리는 "감사 어떤 도움" "감사합니다", 또는 사용하지 않는, 또는 [so]의 서명. "[안녕하세요, '고마워,'태그 라인 및 인사말을 게시물에서 삭제해야합니까?] (http://meta.stackexchange.com/questions/2950/should-hi-thanks-taglines-and-salutations-be 참조) -removed-from-posts) –

답변

1

그래서 좀 더 연구, 머리를 긁적과 친절한 사람들의 도움은 여기에 나를 인도 :

class Program 
{ 
    String[] arrUserData = new String[4];// Must specify 4 in brackets for array length, not the same as an index 
    // it will fill up as items are added to it starting from position 0 automatically 
    // should also be at class level for multiple method access 

    public void Play() 
    { 
     String command; // doesn't need to have an empty string value, only be declared 

     String[] arrQuestions = new String[4];//questions asked 
     arrQuestions[0] = "First Name: "; 
     arrQuestions[1] = "Last Name: "; 
     arrQuestions[2] = "Restaurant Name: "; 
     arrQuestions[3] = "Cost of Meal: "; 

     do { 
      GetString("+ + + Meal Calculator Exercise + + +"); // I removed the one in the top of the method, or else it does it twice 
      // pass in array of questions to satisfy necessary array argument in GetUserData(); 
      GetUserData(arrQuestions);//run loop, ask questions populate arrUserData array 

      command = GetString("Again? "); // your GetString method returns whatever the console reads, 
      // so it can be assigned to your command variable at the same time, or else the user has to put in y or yes twice 
      Console.Clear(); 
     } 
     while (command == "y" || command == "yes"); 

     GetString("+ + + Thank you + + + Have a wonderful time + + + Goodbye! + + +"); 
    } 

    public String GetString(String strTxt) 
    { 
     Console.WriteLine(strTxt); return Console.ReadLine().ToLower().Trim(); 
    } 

    // changed it to a void to it just simply assigns the values to the class level array 
    public void GetUserData(string[] thisArray) 
    { 
     for (int i = 0; i < thisArray.Length; i++)//use the passed in array to determine loop length 
     {// missing curly braces 
      Console.WriteLine(thisArray[i]); // write question with corresponding index to console 
      arrUserData[i] = Console.ReadLine(); // use Console.ReadLine to get input and assign it to corresponding index in userData 
      if (i == 3) // check for the last index to convert to double 
      {// here's the basic way, can cause a lot of errors if user input is not a double 
       Convert.ToDouble(arrUserData[3]); 

       // here's the way trapping all possible errors, and giving a nice message for each 
       // remove the other Convert.ToDouble method and uncomment this to try giving some false values to see how it works 
       /* 
       try 
       { 
        Convert.ToDouble(arrUserData[3]); 
       } 
       catch (FormatException) 
       { 
        Console.WriteLine("Unable to convert " + arrUserData[3] + " to a Double."); 
       } 
       catch (OverflowException) 
       { 
        Console.WriteLine(arrUserData[3] + " is outside the range of a Double."); 
       } 
       * */ 
      } 
     } 
     SeeUserData(thisArray); // to display the user data, demonstrates nesting methods that can 
     // operate off of one single variable pass in your Play method 
     // you could also move it to your play method and change it to SeeUserData(arrQuestions); and it would work the same 
    } 

    public void SeeUserData(string[] sameArrayAgain) 
    { 
     Console.WriteLine("Here's the data for " + arrUserData[0]); 
     for (int i = 0; i < sameArrayAgain.Length; i++) 
     { 
      Console.WriteLine("Your " + sameArrayAgain[i] + " " + arrUserData[i]); 
     } 
    } 

    static void Main(string[] args) { Program myProgram = new Program(); myProgram.Play(); } 
} 
1

안에 앉아있다.

나는 바로 코드에 탐구하지 않습니다하지만 난 그것을 설명하려고합니다 :

내가 배열에있는 질문에 계산 (사항 Array.length)하고 저장할 수 있습니다. 그럼 대답의 질문의 개수가 배열의 길이와 같은지 확인하는 while 루프를 할 것입니다. 이 루프에서 콘솔 readline을 사용하여 질문을 하나씩 배열에 배치하고 카운터 변수를 증가시킨 다음 증가하는 변수를 사용하여 사용자 데이터 배열에 응답을 삽입 할 수 있습니다.

의미가 있습니까? 어떤 설명이 필요한지 또는 이것이 당신이 찾고있는 것이 아닌지 알려주십시오.

+0

적어도 개념적으로 나는 그것을 해결할 수 있는지 알아보기 위해 노력할 것입니다. 지침을 주셔서 감사 드리며 결과를보고 드리겠습니다. – Chezshire

+0

붙어있는 것 같습니다. 배열의 길이를 계산하는 메서드에 배열을 전달하는 데 성공하지 못했습니다. 현재 내 '메서드 호출은'public String GetUserData (arrData) { '로 읽은 다음 메서드 자체가 다음과 같이 읽습니다.'public String GetUserData (arrData) {int i = 0; int step = arrData.Length; do {Console.WriteLine (arrQuestions [i]); arrData [i] = Console.ReadLine(); 나는 ++; } while (i <단계); return arrData; } '나는 arrs를 먹어 치우고 다시 무언가를 얻는다고 생각한다. 그것은 여전히 ​​여송연이다. – Chezshire

+0

이제 'GetUserData (arrUserData);'와 같은 메소드를 호출합니다. 나는 루프를 이렇게 재 작업한다. 'public String [] GetUserData (String [] arrData) { int i = 0; int step = arrData.Length; while (i <= step) { Console.WriteLine (arrQuestions [i]); arrData [i] = Console.ReadLine(); } return arrData; } '아직도 내가 뭘 잘못하고 있는지 모르겠지만, 배열 arrQuestions가 메서드에 들어 가지 않는 것 같습니다. – Chezshire

관련 문제