亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何迭代打印多個值的過程?

如何迭代打印多個值的過程?

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 關注
  • 100 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號