2014-09-10 171 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 { // ... 

我应该提到它与交换机内变化的变量没有任何关系。在交换机内改变变量是完全可以允许的。