简体   繁体   中英

Confused about how to use return in c#

Ai'm new here and new in programming as well. I'm sorry if this question is really childish but i'm having some trouble using return type in a simple c# program. 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. A friend advice to use while loop but I have no idea how to use while loop over here. 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:

 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. 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.

c. try to think of ways to use code to prevent repeating yourself.

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.

hope this helps someone :)

The loop can be implemented in the Debit method:

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. 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:

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. 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. 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);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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