2014-09-10 91 views
3

對於學校作業,我應該創建一個類似ATM的菜單。在C#'switch'語句中更改變量

我的教授給我們這個代碼使用方法:

string choice = null; 

do 
{ 
    Console.Write("[O]pen Account [I]nquire [D]eposit [W]ithdraw [Q]uit: "); 
    choice = Console.ReadLine(); 
    choice = choice.ToUpper(); 

    switch (choice) 
    { 
     case "O": // open an account 
     case "I": // inquire 
     case "D": // deposit 
     case "W": // withdraw 
     default: break; 
    } 
} while (choice != "Q"); 

這裏是我做過什麼:

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

namespace ConsoleApplication1 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      string choice = null; 
      string CustomerName; 

      Console.WriteLine("Welcome to Fantasy Bank"); 
      Console.Write("Please enter your name:"); 
      CustomerName = Console.ReadLine(); 
      do 
      { 
       Console.WriteLine("What can I do for you"); 
       Console.Write("[O]pen Account [I]nquire [D]eposit [W]ithdraw [Q]uit: "); 
       choice = Console.ReadLine(); 
       choice = choice.ToUpper(); 

       double CurrentBalance = 0; 
       switch (choice) 
       { 

        case "O": // open an account 
         Console.Write("Name of account holder:"); 
         Console.WriteLine(CustomerName); 
         Console.Write("Initial Deposit:"); 
         CurrentBalance = Convert.ToDouble(Console.ReadLine()); // i get a major error if someone types in a letter instead of a number 
         Console.Write("You have succesfully opened an account with an initial deposit of "); 
         Console.Write(CurrentBalance); 
         Console.WriteLine(" at an imaginary bank. Congratulations"); 
        break; 
        case "I": // inquire 
         Console.Write(CustomerName); 
         Console.WriteLine("'s Bank Account"); 
         Console.WriteLine(CurrentBalance); 
        break; 

我確實有點多,但這裏的問題開始在case "I"CustomerName正在被用戶鍵入的內容替換,就像它應該的那樣。但CurrentBalance不會更改,我必須將其設置爲等於某些內容,否則會出現錯誤。

我開始覺得可能不可能在switch內更改switch變量。我在我的書中查看傳遞參考/值,但不包括該部分中的switch。 如果你們可以給我提示我做錯了什麼,或者可以告訴我什麼可以解決我的問題,那就太好了。我不期待你的代碼,只是朝正確的方向推進。

回答

5

您的問題是您的CurrentBalance聲明的展示位置

目前你有這樣的:

do 
{ 
    double CurrentBalance = 0; 
    switch (choice) { 
     /* the rest of your code */ 
    } 
} 

應該

double CurrentBalance = 0; 
do 
{ 
    switch (choice) { 
     /* the rest of your code */ 
    } 
} 

現在,您do循環的下一次迭代不重置CurrentBalance0

1

循環的每一次迭代你重置CurrentBalance爲0.移動線double CurrentBalance = 0;

string choice; 
string CurrentName; 
double CurrentBalance = 0; 

// ... 

do 
{ 
    // ... 
    //double CurrentBalance = 0; NOT HERE 
    switch(...) 
    { 

    } 
} 
1

你應該再進循環,不環路初始化所有的變量,否則變量重新初始化(清零0)每次迭代。

double CurrentBalance = 0; 
// other code... 
do { // ... 

我應該提到它與交換機內變化的變量沒有任何關係。在交換機內改變變量是完全可以允許的。