Принятие пользовательского ввода в качестве имени нового экземпляра класса - PullRequest
0 голосов
/ 24 января 2020

Я пытаюсь создать класс в C#, называемый клиентом, с 3 переменными: имя, начальный депозит и ежемесячная сумма депозита.

Это для консольной программы, которая принимает пользовательский ввод для этих трех переменных и продолжает запрашивать больше пользователей, пока пользователь ничего не наберет и не нажмет enter.

Однако строка customer userInputName = new customer(userInputName, userInputInitial, userInputMonthly); выдаёт мне ошибки. Первое userInputName подчеркнуто, говоря , что «локальный или параметр с именем« userInputName »не может быть удален в этой области, потому что это имя используется во внешней локальной области для определения локального или параметра« . Второе 'userInputName' говорит «Аргумент 1: невозможно преобразовать из« lab4.Program.customer »в« строку »» .

Единственный способ исправить это, изменив первое имя пользователя userInput на что-то вроде customer1, но если я это сделаю, я не смогу постоянно заводить новых клиентов, если пользователь продолжит вводить имена.

В идеале я хочу иметь возможность напечатать что-то вроде customer.Bob.initialDeposit и иметь программу, способную сообщить мне, каков был первоначальный депозит Боба, и т. Д. c.

Как мне этого добиться, или что я делаю не так?

using System;

namespace lab4
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("How many months will the customer keep the money in the account?");
            string monthsString = Console.ReadLine();
            int months = Int32.Parse(monthsString);

            bool run = true;
            while (run)
            {
                Console.WriteLine("Enter new customer name: ");

                string userInputName = Console.ReadLine();
                if (userInputName == "")
                {
                    run = false;
                }
                else
                {
                    Console.WriteLine("Enter initial deposit amount: ");
                    string stringInitDeposit = Console.ReadLine();
                    int userInputInitial = Int32.Parse(stringInitDeposit);

                    Console.WriteLine("Enter montly deposit amount: ");
                    string stringMonthDeposit = Console.ReadLine();
                    int userInputMonthly = Int32.Parse(stringMonthDeposit);

                    customer userInputName = new customer(userInputName, userInputInitial, userInputMonthly);
                }

            }
        }


            public class customer
            {
                public string name;
                public int initialDeposit;
                public int monthlyDeposit;

                public customer(string name, int initialDeposit, int monthlyDeposit)
                {
                    this.name = name;
                    this.initialDeposit = initialDeposit;
                    this.monthlyDeposit = monthlyDeposit;
                }
            }
    }
}

Ответы [ 2 ]

1 голос
/ 24 января 2020

У вас есть

string userInputName = Console.ReadLine();

и

customer userInputName = new customer(userInputName, userInputInitial, userInputMonthly);

Вы пытаетесь использовать одно и то же имя переменной. Выберите новый для клиента (так как в любом случае это имя не имеет смысла) и обновите ссылки для использования этого нового имени переменной.

Если вы хотите сделать несколько клиентов, добавьте нового клиента в массив. Переменная может все еще использоваться повторно в течение времени l oop.

Пример:

// add this line outside (above) the while loop: (you will need to import the proper namespace for this: `using System.Collections.Generic;`)
List<Customer> newCustomers = new List<Customer>();


// I renamed this variable. add the line below to put the new customer into the list
customer newCustomer = new customer(userInputName, userInputInitial, userInputMonthly);
newCustomers.Add(newCustomer);

// now you have a list of new customers you can reference outside the while loop.
0 голосов
/ 24 января 2020

Чтобы получить депозит Боба, вы можете сделать что-то вроде следующего:

using System;
using System.Collections.Generic;
using System.Linq;

(...)

var customers = new List<Customer>();

//Your logic to create customers here
var c1 = new Customer("Bob", 100, 10);
customers.Add(c1);
var c2 = new Customer("Bob", 200, 20);
customers.Add(c2);
var c3 = new Customer("Alice", 100, 10);
customers.Add(c3);


//Find all Bobs
var bobs = customers.Where(c => c.Name == "Bob");

foreach (var bob in bobs )
{
    Console.WriteLine($"Bob's initial deposit is {bob.InitialDeposit}");
}

Обратите внимание, что названия классов обычно пишутся с большой буквы, например, Customer.

Это также распространено сохранить поля закрытыми в классах и использовать свойства для доступа publi c.

Вот вариант класса Customer:

public class Customer
{
    public Customer(string name, int initialDeposit, int monthlyDeposit)
    {
        Name = name;
        InitialDeposit = initialDeposit;
        MonthlyDeposit = monthlyDeposit;
    }

    public string Name { get; }
    public int InitialDeposit { get; }
    public int MonthlyDeposit { get; }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...