簡體   English   中英

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

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

Ai是這里的新手,也是編程的新手。 我很抱歉,如果這個問題真的很幼稚,但是在簡單的C#程序中使用return類型遇到了一些麻煩。 這是我的代碼文件,在AccountTest類中的d == 2處,我希望提款過程重新開始,但是這次不要求用戶輸入帳戶余額。 一個朋友建議使用while循環,但是我不知道如何在此處使用while循環。 提前致謝。 :)

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

還有我的帳戶課程

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

確實應該對代碼進行重構。 將帳戶視為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; }
 }

現在,您可以詢問用戶要使用其帳戶做什么,並且您有空間添加多個帳戶。 因此該程序可能看起來像:

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         
}

我將從閱讀靜態對象與實例對象開始

首先,歡迎來到編碼社區,沒有任何幼稚的問題隨時隨地問,有一些人會用“谷歌有答案”來回答您,但是沒有其他很多擔心會幫助您,我已經看到了您選擇了一個答案,但對您和其他新程序員而言,我的觀點不好。

一種。 如果您從未使用過編碼,那么它只會使事情變得復雜,而從流程圖開始,說明您從程序以及從每個組件(類,函數等)獲得的結果,這很容易要將其轉換為代碼,您可以嘗試使用該站點,它看起來非常用戶友好,並且將以正確的格式繪制流程圖。

b。 就像這里的人在我之前說過的那樣,請不要使用a,b,c之類的變量,因為第二天,您將嘗試從上次中斷的地方繼續,而您會忘記自己的意思。

C。 嘗試思考使用代碼防止重復的方法。

d。 使用硬編碼值是不好的做法(硬編碼意味着:

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

到我回答您的問題時,我已經看到了@Jonesy的答案,這是正確的,就像我想建議的那樣,病得很厲害,讓他留他的答案。

希望這可以幫助某人:)

可以使用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);
}

您應該閱讀while循環。 基本上,您想要的是返回一個數字的方法,該數字確定程序下一步應執行的操作或何時結束。 將循環視為您的引擎指出“只要不按下[選擇鍵],就繼續做某事”。

一個小例子,[選擇鍵]為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()); 
    }

}

請注意,這不是功能正常的ATM程序,因為余額永遠不會更新。 我將其留給您解決,因為我猜這是針對編程中的一類=)

好吧,這是我的程序版本。 我稍微改變了行為(例如再次詢問該值何時無效)。 這並不完美; 例如,消息和RequestDebit方法應在Account類之外(也許在AccountHandler類中)處理,但是對於此簡單練習而言,所有這些可能都太過分了。 無論如何,我希望您覺得它有用:

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