簡體   English   中英

如何從 Main() 方法調用類?

[英]How to call a class from Main() method?

我目前正在從事下面列出的項目。 到目前為止,我無法從我的程序訪問我的課程。 我不確定它是否是我遺漏的東西,或者我是否只是在我的腦海中。 我將包括到目前為止我想出的代碼。

你將被評分:

  • 您的代碼必須編譯。 如果您的代碼有編譯錯誤並且沒有運行,您將不會獲得及格分數。
  • 您的代碼必須遵循提供的准則。 例如:您的最終代碼必須包含 3 個類。 如果您的所有代碼都是在 main() 中使用一系列 WriteLine() 方法完成的,那么您將不會做得很好。

威基基希爾頓海灘租賃申請:

您將為 Waikiki Hilton Beach Rentals 創建一個計划。 希爾頓酒店的客人可以在這里租用浮筏、浮潛裝備、椅子、遮陽傘和槳船等海灘設備。

您的應用程序將獲得客人姓名、租借物品、每件租借物品的數量和總租用分鍾數。 客人可以租用任意數量的物品和多個數量。 您可以假設所有項目都是在同一時間范圍內租用的。 因此,客人可以租用 2 把椅子和浮潛裝備——但都需要 65 分鍾。 (不是 15 人的椅子,例如 45 人的浮潛裝備)

您將創建三個類,BeachRentalsApp 將作為程序的入口點,您將用於創建租賃對象的租賃類,以及保存來賓信息的來賓類。

BeachRentalsApp – 程序開始的地方。 這應該創建一個訪客對象。 您的客人對象包含客人姓名、合同編號和一系列租賃對象。 該應用程序應顯示歡迎消息,然后獲取客人信息以及租賃信息。 在 main() 方法中顯示和收集的所有信息都應該從 BeachRentalsApp 類中的方法調用。

包含以下方法:

  • main() – 實例化一個 Guest 對象,並根據需要實例化多個 Rental 對象。 然后將租賃對象存儲在 Guest 對象中的數組數據元素中,即 itemsRented[]。 main 方法應該調用方法來獲取輸入和顯示數據。 在這個類中調用的方法應該包括:
  • 顯示歡迎信息
  • 獲取客人姓名
  • 獲取合同號
  • 租用分鍾 - 客人必須租用至少一個小時但不超過 8 小時。
  • 獲取要出租的物品和數量
  • 顯示來自租賃類的靜態數組
  • 獲取要出租的數量和物品
  • 顯示最終租賃信息:
  • 客人姓名
  • 每件物品:租借物品,總租金(物品價格*租期)
  • 所有租借物品的最終總數

來賓 - 保存來賓信息的類

特性:

  • 客人姓名
  • 合約編號(即K168)
  • # 小時租用
  • # 分鍾租用
  • 租借物品(租借物品數組)

適當的構造函數:需要最少的來賓名稱來實例化來賓對象。

方法:

  • 設置合同編號。 如果未提供編號,則創建一個隨機合同編號。 它應該以客戶名稱的第一個字母開頭,然后隨機生成額外的 4 個數字。
  • 接受租用的分鍾數並相應地設置班級數據字段(# 租用小時數,# 租用分鍾數)。

租賃 – 描述租賃的類

構造器視情況而定。 這個類的用戶需要最少的租用項目來實例化一個對象。

靜態成員:

  • 一系列可用的租賃物品(如浮筏、浮潛裝備、椅子、雨傘、槳船)
  • 以下各項的每小時費率是:
  • 浮筏 – $15
  • 浮潛裝備 – 25 美元
  • 椅子——8 美元
  • 雨傘 – 10 美元
  • 槳船 - 40 美元

特性:

  • 租用物品(即雨傘)
  • 租用數量(即 3 把雨傘)
  • 總租金(即雨傘成本 $10 * 租期 * 3 把雨傘)

方法

  • 顯示可供出租的物品的靜態方法
  • 計算總價 - 以半小時為增量計算。 例如。 一把雨傘每小時收費 8 美元。 如果租用時間為 30 分鍾,則價格為 4 美元。 否則價格為8美元。 因此,租用 75 分鍾的費用為 12 美元。 (1 小時為 8 美元,額外 30 分鍾為 4 美元)45 分鍾的租金為 8 美元。

代碼:

namespace BeachRentalsApp
{
    public class Program
    {
        public static void Main()
        {

            Welcome();
            string[] RentalList = { "1. Floatation Rafts", "2. Snorkel Gear", "3. Chairs", "4. Umbrellas", "5. Paddle Boat" };

            int LenOfArray = RentalList.Length;
            for (int i = 0; i < LenOfArray; i++)
            {
                Console.WriteLine(RentalList[i]);

            }
        }

        public static void Welcome()
        {
            Console.WriteLine("******************************************");
            Console.WriteLine("Welcome to Waikiki Hilton Beach Rentals!");
            Console.WriteLine("******************************************");
            Console.WriteLine("                                          ");
            Console.WriteLine("You will be asked to enter your name and ");
            Console.WriteLine("pick the equipment you would like to rent.");
            Console.WriteLine("We hope that you enjoy your stay at Waikiki");
            Console.WriteLine("and look forward to serving you again soon!");
            Console.WriteLine("                                           ");
            Console.WriteLine("Enter your name to start renting Equipment:  ");
            string GName = Console.ReadLine();
            Console.Clear();
            Console.WriteLine("Thank you {0}! Please take a look at equipment selection!", GName);
        }
    }

    class Rentals
    {
        public int FloatationPrice = 15;
        public int SnorkelPrice = 25;
        public int ChairPrice = 8;
        public int UmbrellaPrice = 10;
        public int PaddlePrice = 40;
        public int RentTime = 65;

        public Rentals()
        {
            string[] RentalSelection = new string[5];
            RentalSelection[0] = "";
            RentalSelection[1] = "";
            RentalSelection[2] = "";
            RentalSelection[3] = "";
            RentalSelection[4] = "";
            Console.Write("Which equipment would you like to rent?");
            RentalSelection[0] = Console.ReadLine();
            Console.Write("Would you like to rent more items?");
        }
    }
}

你可以這樣做:

在此處輸入圖片說明

代碼:

using System;
using System.Collections.Generic;

namespace BeachRentalsApp
{
    internal static class Program
    {
        private static void Main(string[] args)
        {
            Console.WriteLine("Welcome!");

            string name;

            while (true)
            {
                Console.WriteLine("Enter your name:");

                name = Console.ReadLine();

                if (!string.IsNullOrWhiteSpace(name))
                    break;
            }

            Console.WriteLine("Enter your contract number or press Enter to generate one:");

            var contract = Console.ReadLine();

            if (string.IsNullOrWhiteSpace(contract))
            {
                contract = $"{name[0]}{new Random().Next(1000, 10000)}";
                Console.WriteLine($"Generated the following contract number: {contract}");
            }

            var minutes = GetNumber("For how long? (minutes, between 1 and 8 hours):", 60, 60 * 8);

            Console.WriteLine("We have the following items available:");

            var items = Rentals.Items;

            for (var i = 0; i < items.Length; i++)
            {
                var item = items[i];
                Console.WriteLine($"{i + 1}. {item.Name} ({item.Price:C})");
            }

            var dictionary = new Dictionary<Item, Rental>();

            while (true)
            {
                var index = GetNumber("Choose an item or 0 to complete your order:", 0, items.Length);
                if (index == 0)
                    break;

                var quantity = GetNumber("Enter quantity:", 1, 9999);

                var item = items[index - 1];

                if (dictionary.ContainsKey(item))
                {
                    dictionary[item].Duration = minutes;
                    dictionary[item].Quantity += quantity;
                }
                else
                {
                    var rental = new Rental
                    {
                        Duration = minutes,
                        Quantity = quantity
                    };
                    dictionary.Add(item, rental);
                }
            }

            Console.WriteLine();

            var total = 0.0m;

            Console.WriteLine("Here's your bill :)");
            Console.WriteLine();

            foreach (var pair in dictionary)
            {
                var itemName = pair.Key.Name;
                var itemQuantity = pair.Value.Quantity;
                var itemDuration = pair.Value.Duration;
                var itemPrice = pair.Key.Price;
                var itemTotal = Math.Ceiling(itemDuration / 60.0m) * itemPrice * itemQuantity;
                Console.WriteLine($"{itemName}:");
                Console.WriteLine($"\tQuantity = {itemQuantity}");
                Console.WriteLine($"\tDuration = {itemDuration}");
                Console.WriteLine($"\tTotal = {itemTotal:C}");
                Console.WriteLine();
                total += itemTotal;
            }

            Console.WriteLine($"Grand total: {total:C}");

            Console.WriteLine();
            Console.WriteLine("We hope to see you again!");

            Console.WriteLine();
            Console.WriteLine("Press any key to exit.");

            Console.ReadKey();
        }

        private static int GetNumber(string message, int min, int max)
        {
            if (message == null)
                throw new ArgumentNullException(nameof(message));

            while (true)
            {
                Console.WriteLine(message);

                if (int.TryParse(Console.ReadLine(), out var number) && number >= min && number <= max)
                    return number;
            }
        }
    }

    public class Item
    {
        public Item(string name, decimal price)
        {
            if (price <= 0.0m)
                throw new ArgumentOutOfRangeException(nameof(price));

            Name = name ?? throw new ArgumentNullException(nameof(name));
            Price = price;
        }

        public string Name { get; }

        public decimal Price { get; }

        public override string ToString()
        {
            return $"{nameof(Name)}: {Name}, {nameof(Price)}: {Price:C}";
        }

        #region Equality members

        private bool Equals(Item other)
        {
            return string.Equals(Name, other.Name);
        }

        public override bool Equals(object obj)
        {
            if (ReferenceEquals(null, obj))
                return false;
            if (ReferenceEquals(this, obj))
                return true;
            if (obj.GetType() != GetType())
                return false;

            return Equals((Item) obj);
        }

        public override int GetHashCode()
        {
            return Name.GetHashCode();
        }

        #endregion
    }

    public class Rental
    {
        public int Duration { get; set; }

        public int Quantity { get; set; }
    }

    public static class Rentals
    {
        public static Item[] Items { get; } =
        {
            new Item("Flotation Raft", 15.0m),
            new Item("Snorkel Gear", 25.0m)
        };
    }
}

下一步:

  • 通過調試來研究代碼,使用F11逐步完成
  • F1檢查文檔
  • 了解發生了什么
  • 根據需要調整它

有很多方法可以達到相同的結果,這個是:

  • 檢查輸入是否正確
  • 允許使用0退出購買循環

我故意沒有做到 1:1,所以你必須先了解它並修改它,否則很明顯你沒有找到它 :)

另外,告訴你的老師他很笨,這種練習只會讓你更討厭編碼!

一個對象是一個包含關於某個項目的描述性數據的類。 例如,Guest 對象將具有名稱、包含其租賃列表的數據結構等內容。

因此,您應該從創建分配定義的 Guest 對象和分配定義的 Rental 對象開始。

假設你已經創建了你的對象,你需要訪問它們,你如何做到這一點:

public static void Main()
        {

            Welcome(); // Get rid of getting their name in welcome, do it here
            Console.WriteLine("Guest name");  
            String guestName = Console.readLine(); 
            String guestContractNumber = Console.readLine();
            if (guestContractNumber.equals("")
            {
// Generate a random guestContract number if they didn't provide one
            }
            // The guest object is created below.
            Guest guest = new Guest(guestName, guestContractNumber);                                                                        
            // The rental object is supposed to have the rental types
            Rental rental = new Rental();

        }

我希望這可以讓你走上正軌。 要創建一個對象(一個類),您需要:

TestClass testClass = new TestClass();

現在您可以訪問該對象:

 testClass.doSomething();

如果在創建類之前需要能夠從類中訪問數據,則可以在數據成員之前使用 static 關鍵字:

class TestClass
{
public static String testString = "Rental items 1... 2..etc";
}

現在你可以這樣做:

TestClass.testString 

獲取 testString 的值。

如果您需要更多幫助,我會盡力提供幫助,祝您好運。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM