2017-04-05 21 views
-1

真的很困惑這個家庭作業,我不是在尋找答案,而是一些指導。我很困惑我將如何接受用戶輸入,並通過它來從數組中取出這些響應中的一個,具體取決於它們的輸入是1到5.下面是問題。C#在涉及字符串的參數傳遞時感到困惑

創建一個名爲Magic8Ball(控制檯或GUI,您的選擇)的程序。該程序應該包含一個方法(由您編寫),用至少五個字符串聲明一個Magic 8-Ball類型短語的數組,例如「答案似乎確定」(您可以編寫短語或使用傳統的方法 - 谷歌魔法8ball短語來查看它們,你的方法應該接受一個參數,這個參數是短語字符串數組的一個索引,你的方法將顯示與傳入方法的索引相關的短語,例如,如果短語[4]中的字符串是「未來看起來陰天」和調用程序傳遞的值4到你的方法,則該方法將顯示「未來顯得渾濁。」包括錯誤處理在你的方法,所以只有有效的索引將產生輸出。

namespace ConsoleApp7 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      int response; 

      string[] quotes; 
      quotes = new string[5]; 

      { 
       quotes[1] = ("Today is going to be a good day"); 
       quotes[2] = ("Tomorrow is going to rain"); 
       quotes[3] = ("Next month will be blissful"); 
       quotes[4] = ("You are very lucky to be here"); 
       quotes[5] = ("The love of your life notices you"); 
      }; 

      WriteLine("Please enter a number between one and five"); 

      response = Convert.ToInt32(ReadLine()); 

      if (response = quotes[1]) 
      { 

      } 
     } 
    } 
} 
+2

'Console.WriteLine(quotes [response])'? –

+4

這與參數傳遞有什麼關係? –

+0

我很困惑如何接受用戶響應並將其與數組字符串中的一個匹配並獲得結果。我正在嘗試一個if語句,但我得到一個錯誤。 – Ksuby

回答

0
namespace ConsoleApp7 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      int response; 

      string[] quotes = new string [5]; 


      { 
       quotes[0] = ("Today is going to be a good day"); 
       quotes[1] = ("Tomorrow is going to rain"); 
       quotes[2] = ("Next month will be blissful"); 
       quotes[3] = ("You are very lucky to be here"); 
       quotes[4] = ("The love of your life notices you"); 
      } 

      WriteLine("Please enter a number between one and five"); 

      response = Convert.ToInt32(ReadLine()); 


      WriteLine(quotes[response]); 
+0

這工作,謝謝。數組一直困惑着我 – Ksuby

+0

即使你正在考慮你自己的問題,請爲其他人添加額外的評論,可能會發現這個問題在任何方面都很有用。 –

+0

你需要'WriteLine(quotes [response-1]);' – ja72

0

response是從1到5的數字。要獲得與響應對應的數組項(字符串引號),您需要評估quote[response-1]。這是因爲在C#中陣列是基於0的。這意味着5個項目的數組索引爲0..4

class Program 
{ 
    static void Main(string[] args) 
    { 
     string[] quotes = new string[] 
     { 
      "Today is going to be a good day", 
      "Tomorrow is going to rain", 
      "Next month will be blissful", 
      "You are very lucky to be here", 
      "The love of your life notices you" 
     }; 

     int response; 
     int.TryParse(Console.ReadLine(), out response); 
     if (response>=1&&response<=quotes.Length) 
     { 
      Console.WriteLine(quotes[response-1]); 
     } 
     else 
     { 
      Console.WriteLine("Invalid input"); 
     } 
    } 
} 

順便說一句,這個問題與傳遞參數無關。

+0

我試圖添加錯誤處理鏈接,但它一直告訴我,「使用未分配的變量」 – Ksuby

+0

對不起,我修復了一些錯字。代碼現在編譯。 – ja72

+0

什麼是(引號[response-1])? – Ksuby