黑马程序员技术交流社区

标题: 请教一个Hashtable基础问题 [打印本页]

作者: O_o”    时间: 2013-8-9 20:37
标题: 请教一个Hashtable基础问题
为什么我输入一个数字不能转换,急,誰能告诉我哪里出了问题。那个论坛没人給給回答,只好在这试试了。
  1. //把123转换为一二三
  2.             //            //string str = "1一 2二 3三 4四 5五 6六 7七 8八 9九";
  3.             Hashtable ht = new Hashtable();

  4.             string str = "1一 2二 3三 4四 5五 6六 7七 8八 9九";
  5.             string[] strNew = str.Split(new char[]{' '},StringSplitOptions.RemoveEmptyEntries);
  6.             //for (int i = 0; i < strNew.Length; i++)
  7.             //{
  8.             //    Console.Write(str[9]+" ");
  9.             //}
  10.             for (int i = 0; i < strNew.Length; i++)
  11.             {
  12.                 ht.Add(strNew[i][0], strNew[i][1]);
  13.             }
  14.             Console.WriteLine("请输入一个数");
  15.             string input = Console.ReadLine();
  16.          

  17.                 if (ht.ContainsKey(input))
  18.                 {
  19.                     Console.WriteLine(ht[input]);
  20.                 }
  21.                 else
  22.                 {
  23.                     Console.WriteLine(input);
  24.                 }
  25.             
  26.             Console.ReadKey();
复制代码

作者: 小天    时间: 2013-8-10 00:21
因为你往哈希表中添的键值对是字符类型的,而你输入的是一个字符串,所以找不到,将添加哈希表的键值对转换为字符串类型就可以了
代码做如下修改,可以通过
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

namespace Test05
{
    class Program
    {
        static void Main(string[] args)
        {
            //把123转换为一二三
            Hashtable ht = new Hashtable();
            string str = "1一 2二 3三 4四 5五 6六 7七 8八 9九";
            string[] strNew = str.Split(new char[] {' '}, StringSplitOptions.RemoveEmptyEntries);
            //Console.WriteLine(strNew[1]);
            for (int i = 0; i < strNew.Length; i++)
            {
                ht.Add(strNew[i][0].ToString(), strNew[i][1].ToString());
               // Console.WriteLine(strNew[i][1]);
            }
            Console.WriteLine("请输入一个数");
            string input = Console.ReadLine();
            if (ht.Contains(input))
            {
                Console.WriteLine(ht[input]);
            }
            else
            {
                Console.WriteLine(input);
            }
            Console.ReadKey();
        }
    }
}





欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2