简体   繁体   English

对如何在C#中使用return感到困惑

[英]Confused about how to use return in c#

Ai'm new here and new in programming as well. Ai是这里的新手,也是编程的新手。 I'm sorry if this question is really childish but i'm having some trouble using return type in a simple c# program. 我很抱歉,如果这个问题真的很幼稚,但是在简单的C#程序中使用return类型遇到了一些麻烦。 Here is my code file, at d == 2 in AccountTest class, I want the withdrawal process to start over again but this time not asking the user to enter the account balance. 这是我的代码文件,在AccountTest类中的d == 2处,我希望提款过程重新开始,但是这次不要求用户输入帐户余额。 A friend advice to use while loop but I have no idea how to use while loop over here. 一个朋友建议使用while循环,但是我不知道如何在此处使用while循环。 Thanks in advance. 提前致谢。 :) :)

using System;

public class Account
{
    public static void Main(string[] args)
    {
        Console.Write("Enter your account balance: ");
        int AccountBalance = Convert.ToInt32(Console.ReadLine());

        Account.Debit(AccountBalance);
    }

    public static void Debit(int AccountBalance)
    {

        Console.Write("\n\nEnter the amount you want to withdraw in Rs: ");
        int WithdrawalAmount = Convert.ToInt32(Console.ReadLine());

        AccountTest.DebitTest(AccountBalance, WithdrawalAmount);
    }
}

And my Account class 还有我的帐户课程

public class AccountTest
{
    public static int DebitTest(int AccountBalance, int WithdrawalAmount)
    {
        if (WithdrawalAmount > AccountBalance)
        {
            Console.WriteLine("\n\nDebit amount exceeded account balance.");
            Console.ReadLine();
            return 0;
        }
        else if (WithdrawalAmount <= 0)
        {
            Console.WriteLine("\n\nError. Incorrect amount.");
            Console.ReadLine();
            return 0;
        }
        else
        {
            int newBalance = AccountBalance - WithdrawalAmount;
            Console.WriteLine("\n\nWithdrawal was successful. Thankyou for using our services.\n\nPress 1 to exit, 2 to withdraw again, 3 to check your account balance.\n");
            int InputNumber = Convert.ToInt32(Console.ReadLine());

            if (InputNumber == 1)
            {
                Console.ReadLine();
                return 0;
            }

            else if (InputNumber == 2)
            {

                return WithdrawalAmount;
            }

            else if (InputNumber == 3)
            {
                Console.WriteLine("\n\nYour remaining account balance is: {0}", newBalance);
                Console.ReadLine();
                return 0;
            }
        }
        return 0;
    }
}

Really the code should be refactored. 确实应该对代码进行重构。 Treating an Account like a thing makes more sense, in that it should be it's own object, and you should tell it what to do: 将帐户视为thing更有意义,因为它应该是它自己的对象,并且应该告诉它该怎么做:

 public class Account
 {
    public int Balance { get; set; }

    public Account(int startBalance)
    {
        Balance = startBalance;
    }

    public void Debit(int amount) { Balance -= amount; }
    public void Credit(int amount) { Balance += amount; }
 }

Now, you can ask the user what they want to do with their Account, and you have room to add multiple accounts. 现在,您可以询问用户要使用其帐户做什么,并且您有空间添加多个帐户。 So the program may look like: 因此该程序可能看起来像:

int startingAmount = int.Parse(Console.ReadLine());
var account = new Account(startingAmount);

Console.WriteLine("1 to credit, 2 to debit, 0 to exit");
var input = int.Parse(Console.ReadLine());
while (input != 0)
{
   //manipulate account         
}

I'd start by reading up about static vs instance objects 我将从阅读静态对象与实例对象开始

first of, welcome to the coding community there is no childish question feel free to ask when ever you need, there some who will answer you with "google has the answer" but no worries a lot of other will help you, i saw you already selected an answer but ill add my point of view for you and the rest of new programmers. 首先,欢迎来到编码社区,没有任何幼稚的问题随时随地问,有一些人会用“谷歌有答案”来回答您,但是没有其他很多担心会帮助您,我已经看到了您选择了一个答案,但对您和其他新程序员而言,我的观点不好。

a. 一种。 if your new to codding never start with code it will only complicate things, instead start with a flow chart that illustrates what you to achieve from the program and from each component ( classes,functions etc. ) after you got that, its a lot easier to transform it to code, you can try using this site it seems to be very user friendly and will draw you flow charts with the correct format. 如果您从未使用过编码,那么它只会使事情变得复杂,而从流程图开始,说明您从程序以及从每个组件(类,函数等)获得的结果,这很容易要将其转换为代码,您可以尝试使用该站点,它看起来非常用户友好,并且将以正确的格式绘制流程图。

b. b。 like people here said before me never use variable like a,b,c because the next day youll try to continue where you left off and you will forget what you meant. 就像这里的人在我之前说过的那样,请不要使用a,b,c之类的变量,因为第二天,您将尝试从上次中断的地方继续,而您会忘记自己的意思。

c. C。 try to think of ways to use code to prevent repeating yourself. 尝试思考使用代码防止重复的方法。

d. d。 using hard coded values is bad practice (hard coded means this: 使用硬编码值是不好的做法(硬编码意味着:

return "this value to return is hard coded and will never change";

)

by the time i got to answer your question i already saw @Jonesy answer which is right and like what i wanted to suggest so ill leave you with his answer. 到我回答您的问题时,我已经看到了@Jonesy的答案,这是正确的,就像我想建议的那样,病得很厉害,让他留他的答案。

hope this helps someone :) 希望这可以帮助某人:)

The loop can be implemented in the Debit method: 可以使用Debit方法实现循环:

public static void Debit(int AccountBalance)
{
    int result = 0;
    do
    {
        Console.Write("\n\nEnter the amount you want to withdraw in Rs: ");
        var WithdrawalAmount = Convert.ToInt32(Console.ReadLine());

        result = AccountTest.DebitTest(AccountBalance, WithdrawalAmount);

    } while (result != 0);
}

You should read up on while loops. 您应该阅读while循环。 Basically what you'd want is the method to return a number that decides what the program is supposed to do next, or when it should end. 基本上,您想要的是返回一个数字的方法,该数字确定程序下一步应执行的操作或何时结束。 Think of the loop as your engine that states "As long as [chosen key] is not pressed, keep doing something". 将循环视为您的引擎指出“只要不按下[选择键],就继续做某事”。

A small example, with [chosen key] being 1, would be: 一个小例子,[选择键]为1,将是:

int choice = 0;
int balance = 100;
while (choice != 1) {
    Console.WriteLine("Enter withdraw amount");
    string userInput = Console.ReadLine();

    // This will crash the program if the user enters text.
    // Used for demonstration only. int.TryParse is preferred.
    int value = int.Parse(userInput);

    choice = AccountTest.DebitTest(balance, value);
}

class AccountTest {
    public static int DebitTest(int AccountBalance, int WithdrawalAmount)
    {
        // do the test if the debit is OK
        //..........

        // At the end, you can do this. This till return the value entered and 
        // choice will be given a new value. If it was 1, the program will end.
        // NOTE: It's not safe to use convert as                
        // it will crash the program if the user enters text.
        return Convert.ToInt32(Console.ReadLine()); 
    }

}

Note that this is not a functional ATM-program, as the balance never gets updated. 请注意,这不是功能正常的ATM程序,因为余额永远不会更新。 I leave that for you to solve since I'm guessing this is for a class in programming =) 我将其留给您解决,因为我猜这是针对编程中的一类=)

Well, this is my version of your program. 好吧,这是我的程序版本。 I changed the behavior a bit (like asking again when the value is invalid). 我稍微改变了行为(例如再次询问该值何时无效)。 It's not perfect; 这并不完美; for example, the messages and the RequestDebit method should be handled outside the Account class, perhaps in an AccountHandler class, but all this might be overkill for this simple exercise. 例如,消息和RequestDebit方法应在Account类之外(也许在AccountHandler类中)处理,但是对于此简单练习而言,所有这些可能都太过分了。 Anyway I hope you find it useful: 无论如何,我希望您觉得它有用:

public class Account
{
    public int Balance { get; set; }

    public Account(int startingBalance)
    {
        this.Balance = startingBalance;
    }

    private bool Debit(int amount)
    {
        if (amount <= 0)
        {
            Console.WriteLine("\n\nError. Incorrect amount.");
            return false;
        }

        if (amount > this.Balance)
        {
            Console.WriteLine("\n\nDebit amount exceeded account balance.");
            return false;
        }

        this.Balance -= amount;
        Console.WriteLine("\n\nWithdrawal was successful. Thankyou for using our services.");
        return true;
    }

    public void RequestDebit()
    {
        bool success;
        do
        {
            Console.Write("\n\nEnter the amount you want to withdraw in Rs: ");
            int withdrawalAmount = Convert.ToInt32(Console.ReadLine());
            success = this.Debit(withdrawalAmount);
        } while (!success);
    }
}

class Program
{
    static void Main(string[] args)
    {
        int accountBalance;
        do
        {
            Console.Write("Enter your account balance: ");
            accountBalance = Convert.ToInt32(Console.ReadLine());
        } while (accountBalance <= 0);

        var myAccount = new Account(accountBalance);

        myAccount.RequestDebit();

        int inputNumber;
        do
        {
            Console.WriteLine("\n\nPress 1 to exit, 2 to withdraw again, 3 to check your account balance.\n");
            inputNumber = Convert.ToInt32(Console.ReadLine());
            switch (inputNumber)
            {
                case 2: myAccount.RequestDebit();
                    break;
                case 3:
                    Console.WriteLine("\n\nYour remaining account balance is: {0}", myAccount.Balance);
                    break;
            }

        } while (inputNumber != 1);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM