1

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;
    }
}
10
  • 3
    Google is plenty of resources: msdn.microsoft.com/en-us/library/2aeyhxcd.aspx (while (C# Reference)), and the search result: google.ca/… Commented Nov 4, 2014 at 15:44
  • You don't need a loop, you can call Debit(c) as c is the new balance.
    – Philippe
    Commented Nov 4, 2014 at 15:46
  • 3
    meaningful variable names will help everyone who tries to read your code Commented Nov 4, 2014 at 15:49
  • 1
    Your code would be a lot more readable if you replaced a, b and d with names such as withdrawlAmount, currentBalance and so on
    – Liath
    Commented Nov 4, 2014 at 15:49
  • 2
    The main problem is that your logic is scattered along all the code. Should the debit method give you the options menu? Certainly not. You should have your main logic (menu with options and loop) in the Main method. I bet many alternative solutions are being prepared as I type, just wait. :)
    – Andrew
    Commented Nov 4, 2014 at 15:51

5 Answers 5

3

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

1

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

3
  • Thanks alot for taking some time out and typing this, it really helps as coding is new to me. :) But I have a question.. what do you mean "prevent repeating yourself"? As in looping?
    – Ali
    Commented Nov 4, 2014 at 16:26
  • there are a lot of places where we can be "lazy" and use the same line of code over and over like if you want to check if string is null or empty you can write this: if(str==null || str == string.Empty) (notice the string.Empty ill explain it later) or you can write a function that does that ( all the old coders here i know there is a function in the String object it was for the demo ), if you keep using the if statement thats repeating.
    – Liran
    Commented Nov 4, 2014 at 16:41
  • now for the reason i said notice the "string.Empty" its like when i said all variables has to mean something string.Empty means that you meant for it to be there and difference between string.Empty and "" is in our head, you will see that as you code more there will be some places you will leave "" to be filled later and so when you see string.Empty you know noting should replace it.
    – Liran
    Commented Nov 4, 2014 at 16:41
0

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

0

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.