亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在C#中的字典中進行用戶輸入?

如何在C#中的字典中進行用戶輸入?

C#
牛魔王的故事 2023-08-20 14:48:53
我想制作一本接受用戶輸入和空格的字典。字典接受輸入字符串和整數。我嘗試通過數組提供輸入,但不知道如何在兩個數組中同時使用空格進行用戶輸入。Dictionary<string, int> Directory = new Dictionary<string, int>();int n = int.Parse(Console.ReadLine());string[] name = new string[n];int[] phone_no = new int[n];for (int i = 0; i < n; i++)}    name[i] = Console.ReadLine();    phone_no[i] = int.Parse(Console.ReadLine());}for (int i = 0; i < n; i++){    Directory.Add(name[i], phone_no[i]);}我需要幫助進行用戶輸入,例如:1.山姆 123456782.哈里25468789
查看完整描述

3 回答

?
慕斯709654

TA貢獻1840條經驗 獲得超5個贊

請注意,電話號碼不是整數,而是字符串。它可能以零開頭,如果您將其解析為 int,則會丟失前導零(0123456789 變為 123456789)。另外,我認為“+31 (0)6-12345678”是一個有效的電話號碼。


這是一個可以完成您想要的操作的示例。它會不斷請求輸入,直到用戶輸入“exit”并用電話號碼更新姓名。


public static void Main()

{

    var directory = new Dictionary<string, string>();


    // Keep requesting inputs

    while (true)

    {

        string input = Console.ReadLine();


        // provide a possibility to break the loop.

        if (input == "exit")

        {

            break;

        }


        string[] items = input.Split(' ', StringSplitOptions.RemoveEmptyEntries);

        if (items.Length != 2)

        {

            Console.WriteLine("Expecting '{Name} {Phonenumber}'");

            continue;

        }


        directory[items[0]] = items[1];

    }


    // TODO: Do something with directory

}


查看完整回答
反對 回復 2023-08-20
?
精慕HU

TA貢獻1845條經驗 獲得超8個贊

您可以使用 String.Split() 分割行,即


var pair = Console.ReadLine().Split(' ');

Dictionary.Add(pair[0], int.Parse(pair[1]))


查看完整回答
反對 回復 2023-08-20
?
藍山帝景

TA貢獻1843條經驗 獲得超7個贊

static void Main(string[] args)

    {

        Dictionary<string, int> Directory = new Dictionary<string, int>();

        Console.WriteLine("Enter the Number of inputs");

        int count = int.Parse(Console.ReadLine());

        for (int i = 0; i < count; i++)

        {

            Console.WriteLine("Enter the Name " + i + 1 + " : ");

            string Name = Console.ReadLine();

            Console.WriteLine("Enter the Age " + i + 1 + " : ");

            int Age = Convert.ToInt32(Console.ReadLine());

            Directory.Add(Name, Age);

        }

        Console.WriteLine("Press key to display the contents of your dictionary..");

        Console.ReadLine();

        foreach (var item in Directory)

        {

            Console.WriteLine("Name : " + item.Key);

            Console.WriteLine("Age : " + item.Value);

        }

        Console.ReadLine();

    }

工作小提琴


查看完整回答
反對 回復 2023-08-20
  • 3 回答
  • 0 關注
  • 154 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號