我刚刚开始研究IT,我认为编写一个小程序向您显示明天是一件很有趣的事情。可悲的是我被困住了。当前,当您从数组中写入正确的数字时,它可以正常工作,但是我希望它可以与字符串一起工作。因此,当您编写“ Maandag”(荷兰语星期一)时,程序将回答Dinsdag(荷兰语星期二)
到目前为止,这是我的代码:
Campaign
答案 0 :(得分:1)
在天数组中取值范围以获取其索引的值。检查是否传递了字符串,并获取匹配的字符串索引的值。然后使用该索引获取第二天的值:
package main
import (
"fmt"
)
var (
counter int
day string
)
func main() {
var dag [7]string
dag[0] = "Zondag"
dag[1] = "Maandag"
dag[2] = "Dinsdag"
dag[3] = "Woensdag"
dag[4] = "Donderdag"
dag[5] = "Vrijdag"
dag[6] = "Zaterdag"
fmt.Println("Welke dag is het?")
fmt.Scan(&day)
for key, value := range dag {
if day == value {
counter = key
}
}
fmt.Println(counter)
if counter == 6 {
counter = 0
fmt.Println(dag[counter])
}
if counter != 6 {
counter = counter + 1
fmt.Println(dag[counter])
}
}
或者如Peter所建议的,您也可以使用地图,这种地图在这种情况下更方便易用:
package main
import (
"fmt"
)
func main() {
var value string
dag := make(map[string]string)
dag["Zondag"] = "Maandag"
dag["Maandag"] = "Dinsdag"
dag["Dinsdag"] = "Woensdag"
dag["Woensdag"] = "Donderdag"
dag["Donderdag"] = "Vrijdag"
dag["Vrijdag"] = "Zaterdag"
fmt.Println("Welke dag is het?")
fmt.Scan(&value)
fmt.Println(dag[value])
}
在Go Playground上工作的代码
答案 1 :(得分:0)
您可以枚举数组并传输数字和字符串
func GetNextDay(someday string){
for i, v := range dag{
if v == someday {
if i==6 {
i = 0
}else {
i = i + 1
}
return dag[i]
}
}
return "no such day in a week"
}
答案 2 :(得分:0)
您正在寻找的是枚举。在Go中,可以这样实现:
type Weekday int
const (
Sunday Weekday = iota
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
)
func (day Weekday) String() string {
// declare an array of strings
// ... operator counts how many
// items in the array (7)
names := [...]string{
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday"}
// → `day`: It's one of the
// values of Weekday constants.
// If the constant is Sunday,
// then day is 0.
// prevent panicking in case of
// `day` is out of range of Weekday
if day < Sunday || day > Saturday {
return "Unknown"
}
// return the name of a Weekday
// constant from the names array
// above.
return names[day]
}
// will display "Sunday"
fmt.Println(Sunday)
// will display "Monday"
fmt.Println(Sunday + 1)
如果不需要int底层类型,则可以这样创建它:
const (
Sunday = "Sunday"
//...
)