为了账号安全,请及时绑定邮箱和手机立即绑定

如何迭代打印多个值的过程?

如何迭代打印多个值的过程?

Go
MM们 2023-02-06 19:09:51
在这段 golang 代码中,我要求一个人输入他的名字。输入名称后,数据将从values1变量中获取,结果,它们将像这样使用给定的键打印出来给定结果Enter your name: samenameHere is the name: samenameHere is the email address: email oneHere is the job role: job one我还想打印values2被注释的变量的数据。同样,如果我有值的数量,我是否必须一次又一次n地重复?for i := range values1要求的结果Enter your name: samenameHere is the name: samenameHere is the email address: email oneHere is the job role: job role oneHere is the name: samenameHere is the email address: email twoHere is the job role: job role two......代码package mainimport "fmt"func main() {    var name string    keys := [3]string{"name", "email address", "job role"}    values1 := [3]string{"samename", "email one", "job role one"}    // values2 := [3]string{"samename", "email two", "job role two"}    for {        fmt.Printf("Enter your name: ")        fmt.Scanln(&name)        fmt.Println()        if name == values1[0] {            for i := range values1 {                // j is index into keys                j := i % len(keys)                // Print blank line between groups.                if j == 0 && i > 0 {                    fmt.Println()                }                fmt.Printf("Here is the %s: %s\n", keys[j], values1[i])            }            break        } else {            fmt.Println("Name is not found. Try again!")        }    }}
查看完整描述

1 回答

?
紫衣仙女

TA贡献1839条经验 获得超15个赞

如果您需要打印密钥,也许您可以使用map. 你可以打印键和map值。


package main


import "fmt"


func main() {

    var name string

    value1 := map[string]string{"name": "samename", "email": "email one", "role": "job role one"}

    value2 := map[string]string{"name": "samename", "email": "email two", "role": "job role two"}

    values := []map[string]string{value1, value2}

    var found bool


    for {

        fmt.Printf("Enter your name: ")

        fmt.Scanln(&name)

        fmt.Println()


        for _, value := range values {

            if value["name"] == name {

                found = true

                for k, v := range value {

                    fmt.Printf("Here is the %s: %s\n", k, v)

                }

                fmt.Println()

            }

        }


        if found {

            break

        } else {

            fmt.Println("Name is not found. Try again!")

        }

    }

}


查看完整回答
反对 回复 2023-02-06
  • 1 回答
  • 0 关注
  • 71 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信