2013-01-04 18 views
3

因此,我正在編寫一個應該花一年時間才能出生的程序,然後告訴他們他們多大年紀以及他們出生年份的事實。在1950年至2012年之間用事實和年齡列出一個Hashtable,現在我試圖讓他們在有人進入一年時輸出。現在它正在做的是花一年的時間,做我想要得到的計算和正確的年齡數,但它與哈希表的直接相反(例如,如果你說你是在1950年出生的,程序會給出答覆,它應該給那些表示他們的出生年份是2012年的人等)。我的HashTable正在扭轉它的輸出

這是迄今爲止的代碼。我希望有一種方法可以解決它,而無需從頭開始。

Imports System 
Imports System.Collections 

Module Module1 
    Sub Main() 
    Console.WriteLine("This program tells you your age based off of your birth year, and gives you a fact about that year. Please note, this year does not account for the recent year change to 2013 due to the majority of the work on it being done prior to 2013") 
    Dim Years As New Hashtable 
    Years.Add(0, "You are most likely less than 1 year old, your birth year (2012) was the year that the US Embassy in Lybia was attacked, leaving the US ambassador dead.") 
    Years.Add(1, "You are most likely 1 year old, your birth year (2011) was the year that Osama Bin Laden, the master mind behind the September 11th attacks, was killed by Seal Team 6 in Pakistan.") 

    Console.WriteLine("Please input the year of your birth.") 
    Dim x As Integer 
    Dim Y As Integer 
    Try 
     x = Console.ReadLine 
    Catch ex As InvalidCastException 
     Console.WriteLine("Please input a year between 1950 and 2012, the program will not work with an empty number.") 
     End 
    End Try 
    Y = 2012 - x 
    Console.WriteLine(Years.Values(Y)) 
    Console.ReadKey() 
    End Sub 
End Module 

我刪除了大部分的哈希表的,以不張貼文字的牆作爲哈希表是63個單位長,但我留在一對夫婦的情況下,問題在於我怎麼做他們。除了事實和數字之外,它們都是相同的。

回答

2

HashTable需要key,正如您從Add(key, value)方法中可以看到的那樣。

要訪問基礎上,key(年)的數據,你會怎麼做:

Console.WriteLine(Years(x)) 

其中x是一年(或key)。

+1

所以,如果我把所有的鑰匙改爲年代而不是應該工作的年齡?只要放下減法部分? – alex21296

+0

這就是我會做的。如果你願意的話,你也可以放棄'.Values'部分..但使用年份作爲關鍵(對我來說)更有意義 –

+0

Ohhhhh好的非常感謝你 – alex21296

0

爲什麼不創建一個包含所有事實的字符串數組?那麼你可以做

Dim facts as String() = {"fact0", "fact1", ...} 
Dim Y as String = facts(2012 - x) 'Y is your value