【问题标题】:C# - Print out a key and its value in a dictionary depending on a users input?C# - 根据用户输入在字典中打印出一个键及其值?
【发布时间】:2017-02-09 06:12:29
【问题描述】:

我又来了:D

这是我当前的代码:

   class Program
    {
        static void Main(string[] args)
        {
            // Declare all numbers
            int electronNumber;
            int protonNumber;
            float neutronNumber;
            int i;
            int indexOfElementName;
            int restartInt;
            restartInt = 1;

            // Declare all strings
            string elementRequest;
            string restartString;

            var elementDictionary = new Dictionary<string, string>
            {
            { "Hydrogen", "H" },
            { "Helium", "He" },
            { "Lithium", "Li" },
            { "Beryllium", "Be" },
            { "Boron", "B" },
            { "Carbon", "C" },
            { "Nitrogen", "N" },
            { "Oxygen", "O" },
            { "Fluroine", "F" },
            { "Neon", "Ne" },
            { "Sodium", "Na" },
            { "Magnesium", "Mg" },
            { "Aluminium", "Al" },
            { "Silicon", "Si" },
            { "Phosphorus", "P" },
            { "Sulfur", "S" },
            { "Chlorine", "Cl" },
            { "Argon", "Ar" },
            { "Potassium", "K" },
            { "Calcium", "Ca" },
            { "Scandium", "Sc" },
            { "Titanium", "Ti" },
            { "Vanadium", "V" },
            { "Chromium", "Cr" },
            { "Manganese", "Mn" },
            { "Iron", "Fe" },
            { "Cobalt", "Co" },
            { "Nickel", "Ni" },
            { "Copper", "Cu" },
            { "Zinc", "Zn" },
            { "Gallium", "Ga" },
            { "Germanium", "Ge" },
            { "Arsenic", "As" },
            { "Selenium", "Se" },
            { "Bromine", "Br" },
            { "Krypton", "Kr" },
            { "Rubidium", "Rb" },
            { "Strontium", "Sr" },
            { "Yttrium", "Y" },
            { "Zirconium", "Zr" },
            { "Niobium", "Nb" },
            { "Molybdenum", "Mo" },
            { "Technetium", "Tc" },
            { "Ruhenium", "Ru" },
            { "Palladium", "Pd" },
            { "Silver", "Ag" },
            { "Cadmium", "Cd" },
            { "Indium", "In" },
            { "Tin", "Sn" },
            { "Antimony", "Sb" },
            { "Tellurium", "Te" },
            { "Iodine", "I" },
            { "Xenon", "Xe" },
            { "Caesium", "Cs" },
            { "Barium", "Ba" },
            { "Lanthanum", "La" },
            { "Cerium", "Ce" },
            { "Praesodynium", "Pr" },
            { "Neodynium", "Nd" },
            { "Promethium", "Pm" },
            { "Samarium", "Sm" },
            { "Europium", "Eu" },
            { "Gadolinium", "Gd" },
            { "Terbium", "Tb" },
            { "Dysprosium", "Dy" },
            { "Holmium", "Ho" },
            { "Erbium", "Er" },
            { "Thulium", "Tm" },
            { "Ytterbium", "Yb" },
            { "Lutetium", "Lu" },
            { "Hafnium", "Hf" },
            { "Tantalum", "Ta" },
            { "Tungsten", "W" },
            { "Rhenium", "Re" },
            { "Osmium", "Os" },
            { "Iridium", "Ir" },
            { "Platinum", "Pt" },
            { "Gold", "Au" },
            { "Mercury", "Hg" },
            { "Thallium", "Tl" },
            { "Lead", "Pb" },
            { "Bismuth", "Bi" },
            { "Polonium", "Po" },
            { "Astatine", "At" },
            { "Radon", "Rn" },
            { "Francium", "Fr" },
            { "Radium", "Ra" },
            { "Actinium", "Ac" },
            { "Thorium", "Th" },
            { "Protactinium", "Pa" },
            { "Uranium", "U" },
            { "Neptunium", "Np" },
            { "Plutonium", "Pu" },
            { "Americium", "Am" },
            { "Curium", "Cm" },
            { "Berkelium", "Bk" },
            { "Californium", "Cf" },
            { "Einsteinium", "Es" },
            { "Fermium", "Fm" },
            { "Mendelevium", "Md" },
            { "Nobelium", "No" },
            { "Lawrencium", "Lr" },
            { "Rutherfordium", "Rf" },
            { "Dubnium", "Db" },
            { "Seaborgium", "Sg" },
            { "Bohrium", "Bh" },
            { "Hassium", "Hs" },
            { "Meitnerium", "Mt" },
            { "Darmstadtium", "Ds" },
            { "Roentgenium", "Rg" },
            { "Copernicium", "Cn" },

            };
                while (restartInt == 1)
            {
                Console.WriteLine("What element do you want? Either input it's full name, with a capital letter. E.g 'Hydrogen'");
                elementRequest = Console.ReadLine();
                string elementSymbol = elementDictionary[elementRequest];
                Console.WriteLine("Your element: " + elementRequest + " has the element symbol of: " + elementSymbol);

                    Console.WriteLine("Would you like to try again? Type '1' for yes, and '2' for no.");
                restartString = Console.ReadLine();
                int.TryParse(restartString, out restartInt);


            };
        }
    }

由于字典列表是按元素各自原子序数的顺序排列的,我如何从开始数到输入的元素,以便找到元素的原子序数。另外,我怎样才能简单地打印出元素名称和它的符号?

例如:

elementRequest = "Nitrogen" 应该打印出来:

元素名称 - “氮” 元素符号 - “N” 元素的原子序数 = 7

我试图做一个循环,为字典中的每个添加添加 1,但它一直输出原子序数作为字典中的项目总数。

对于名称和符号的打印(“Nitrogen”,“N”),这里的另一个出色的助手告诉我如何获取符号,但是行:

string elementSymbol = elementDictionary[elementRequest];

只打印出它的符号,而不是它的元素名称和它的符号,我不完全确定为什么或如何修复它。通过放入 [elementRequest] 肯定会找到“Hydrogen”和“H”吗?还是我误会了什么?

感谢任何帮助! :D

【问题讨论】:

  • 你能展示一下你目前尝试过的循环吗?
  • 如果要保存元素的顺序,应该使用 List>,因为字典不保证顺序。
  • 我删除了它,因为它不起作用。现在我考虑了一下,我是否可以在字典中添加第三部分以获取原子序数,因为数字不会改变,然后只打印它的所有 3 个部分?这也会使想法过时,因为顺序无关紧要,因为数字将与其原子名称一起存储。 @ltiveron 将替换行 var elementDictionary = new Dictionary

标签: c# dictionary input output


【解决方案1】:

也许尝试一个类来表示元素。

public class Element
{
    public string Name { get; set; }
    public string Symbol { get; set;}
    public int AtomicNumber { get; set; }

    public Element(string name, string symbol, int atomicNumber)
    {
        Name = name;
        Symbol = symbol;
        AtomicNumber = atomicNumber;
    }
}

像这样添加到字典中:

var elementDictionary = new Dictionary<string, Element>
{
        { "Hydrogen", new Element("Hydrogen", "H", 1) },
        { "Helium", new Element("Helium", "He", 2) },

        //etc.
};

然后当你在字典中查找时,你会得到这个类,这样就可以访问它的所有属性

elementRequest = Console.ReadLine();
var element = elementDictionary[elementRequest];
Console.WriteLine("Your element: " + element.Name + " has the element symbol of: " + element.Symbol + " and atomic number of: " + element.AtomicNumber);

然后,您可以向元素类添加更多属性,并在从字典中检索时使它们全部可用

编辑 - 完整的代码测试和工作

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication4
{
    class Program
    {
        static void Main(string[] args)
        {
            int restartInt;
            restartInt = 1;

            // Declare all strings
            string elementRequest;
            string restartString;

            var elementDictionary = new Dictionary<string, Element>
            {
                { "Hydrogen", new Element("Hydrogen", "H", 1) },
                { "Helium", new Element("Helium", "He", 2) },

                //etc.
            };

            while (restartInt == 1)
            {
                Console.WriteLine("What element do you want? Either input it's full name, with a capital letter. E.g 'Hydrogen'");

                elementRequest = Console.ReadLine();
                var element = elementDictionary[elementRequest];
                Console.WriteLine("Your element: " + element.Name + " has the element symbol of: " + element.Symbol + " and atomic number of: " + element.AtomicNumber);

                Console.WriteLine("Would you like to try again? Type '1' for yes, and '2' for no.");
                restartString = Console.ReadLine();
                int.TryParse(restartString, out restartInt);
            };
        }
    }


    public class Element
    {
        public string Name { get; set; }
        public string Symbol { get; set; }
        public int AtomicNumber { get; set; }

        public Element(string name, string symbol, int atomicNumber)
        {
            Name = name;
            Symbol = symbol;
            AtomicNumber = atomicNumber;
        }
    }
}

【讨论】:

  • 这看起来不错。你知道更多关于课程的信息吗?我想了解他们!
  • 如果您要编写 c# 代码,这是一个基本原则 - 只需 google “c# class”,您会发现很多信息!
  • 使用此代码时,我收到一个 var 错误,指出“上下文关键字“var”可能只出现在局部变量声明或脚本代码中。我应该将它移到哪里?也许在公共类的括号?
  • 代码运行正常,我不知道你为什么会出现这个错误
  • 哦,我明白了 - 您应该将后两段代码放在原始代码所在的位置 - 即在您的静态 void Main 方法中。第一段代码(Element 类)应该在 Program 类之后。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-05
  • 1970-01-01
  • 2019-12-12
  • 2021-07-02
相关资源
最近更新 更多