Hackerrank / 30天代码/天8

时间:2016-09-16 18:34:15

标签: c#

请帮助我理解, 我目前正在参与30天的代码。我在第8天,这是关于C#中的字典。我去运行我的代码,但hackerrank显示致命错误。但是,当我在visual studio中运行我的代码时,一切都按预期运行。这是我的代码。谢谢

using System;
using System.Collections.Generic;
using System.IO;
class Solution {
    static void Main(String[] args) {
        /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution */
        int N, phoneNum;
        string name;


        N = Convert.ToInt32(Console.ReadLine());

        Dictionary<string, int> phoneBook = new Dictionary<string, int>();
        for(int index = 0; index < N; ++index)
        {
            name = Console.ReadLine();
            phoneNum = Convert.ToInt32(Console.ReadLine());
            phoneBook.Add(name, phoneNum);
        }

        for(int index = 0; index < N; ++index)
        {
            name = Console.ReadLine();
            if(phoneBook.ContainsKey(name) == true)
                Console.WriteLine("{0}={1}",name, phoneBook[name]);
            else
                Console.WriteLine("Not found");
        }


    }
}

错误:

Unhandled Exception: System.FormatException: Input string was not in a correct format. at System.Number.StringToNumber (System.String str, NumberStyles options, System.NumberBuffer& number

2 个答案:

答案 0 :(得分:1)

感谢您的回复。在我的无知中,我没有意识到&#34;关键&#34;并且值作为一个字符串输入。但是,从逻辑上说这是愚蠢的。我会有两个特定于键和值的变量。这是我更新的代码。

using System;
using System.Collections.Generic;
using System.IO;
class Solution {
    static void Main(String[] args) {
        /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution */
        int N;
        string dumbAssInput, name, phoneNum;


        N = Convert.ToInt32(Console.ReadLine());

        Dictionary<string, string> phoneBook = new Dictionary<string, string>();
        for(int index = 0; index < N; ++index)
        {
            dumbAssInput = Console.ReadLine();
            string[] keyAndValue = dumbAssInput.Split(' ');
            name = keyAndValue[0];
            phoneNum = keyAndValue[1];
            phoneBook.Add(name, phoneNum);
        }

        for(int index = 0; index < N; ++index)
        {
            name = Console.ReadLine();
            if(phoneBook.ContainsKey(name) == true)
                Console.WriteLine("{0}={1}",name, phoneBook[name]);
            else
                Console.WriteLine("Not found");
        }


    }
}

答案 1 :(得分:1)

[i]

因为 Unknow .i.e。然后,您将获得一个未知数量的名称来查询您的电话簿。