在C#’switch’语句中更改变量
发布时间:2020-12-16 02:03:15 所属栏目:百科 来源:网络整理
导读:对于学校作业,我应该创建一个类似ATM的菜单. 我的教授给了我们这段代码: 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)
对于学校作业,我应该创建一个类似ATM的菜单.
我的教授给了我们这段代码: 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; 我做了一点点,但问题从“I”开始. CustomerName正在被用户输入的内容所取代,就像它应该的那样.但是CurrentBalance不会改变,我必须将它设置为等于某些东西,否则我会收到错误. 我开始觉得可能无法更改开关内的开关变量.我查看了我的书中传递引用/值,但它不包括该部分中的开关. 解决方法
您的问题是您的CurrentBalance声明的位置.
目前你有这个: do { double CurrentBalance = 0; switch (choice) { /* the rest of your code */ } } 应该 double CurrentBalance = 0; do { switch (choice) { /* the rest of your code */ } } 现在,do循环的下一次迭代不会将CurrentBalance重置为0 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |