我的索引超出范围,我开始恐慌,我无法脱身

我正在编写这个程序来适应类型(而不是对象!)。


基本前提是用户输入一个动物名称(牛、蛇鸟),然后输入一个动作(吃、移动、声音)。然后我的代码查找它并返回值。


因此,假设用户条目位于由“”分隔的一行。我使用strings.Split。


当用户只输入一个字符时,我会收到“恐慌”通知。我认为这种恐慌源于编译器试图“拆分”单个字符。


两个问题: 1. 我说的对吗?2. 我该如何解决?


package main


import (

    "bufio"

    "fmt"

    "os"

    "strings"

)


//Create our type object.

type animal struct {

    aType, eats, moves, sounds string

}


//Create our methods.

func (animal animal) info (querie string) {

    if querie == "eats" {

        fmt.Printf("The animal, %s , eats %s\n ", animal.aType, animal.eats)

    } else if querie == "moves" {

        fmt.Printf("The animal, %s , moves by  %s\n ", animal.aType, animal.moves)

    } else {

        fmt.Printf("The animal, %s , makes the sound %s\n ", animal.aType, animal.sounds)

    }

}


func main() {

    //Now create our animals


    cow := animal{aType:"cow", eats: "grass", moves: "walking", sounds: "moo"}

    bird := animal{aType:"bird", eats: "worms", moves: "flying", sounds: "peep"}

    snake := animal{aType:"snake", eats: "mice", moves: "slithering", sounds: "hiss"}

    // need a boolean to perpetuate our loop

    var flag bool = true


    for flag {

        fmt.Println("Remember enter X to exit")

        fmt.Printf(">please enter your (format: type & information) request -> ")

        scanner := bufio.NewScanner(os.Stdin)

        scanner.Scan()

        request := scanner.Text()


        //Capture user entered data


        typed := strings.Split(request, " ")[0]

        if typed == "X" {

            flag = false

            break

        }

        infoe := strings.Split(request, " ")[1]


        // contruct the logic tree. 


        if !((infoe == "eat") || (infoe == "move") || (infoe == "speak")) {

            switch typed {

            case "cow": 

                cow.info(infoe)


            case "snake": 

                snake.info(infoe)

月关宝盒
浏览 118回答 2
2回答

UYOU

在循环外创建扫描仪以避免丢弃缓冲数据。当 Scan() 返回 false 时中断。检查并处理无效输入。scanner := bufio.NewScanner(os.Stdin)for {&nbsp; &nbsp; fmt.Println("Remember enter X to exit")&nbsp; &nbsp; if !scanner.Scan() {&nbsp; &nbsp; &nbsp; &nbsp; break&nbsp; &nbsp; }&nbsp; &nbsp; request := scanner.Text()&nbsp; &nbsp; parts := strings.Split(request, " ")&nbsp; &nbsp; if parts[0] == "X" {&nbsp; &nbsp; &nbsp; &nbsp; break&nbsp; &nbsp; }&nbsp; &nbsp; if len(parts) < 2 {&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println("bad input")&nbsp; &nbsp; &nbsp; &nbsp; break&nbsp; &nbsp; }&nbsp; &nbsp; typed := parts[0]&nbsp; &nbsp; infoe := parts[1]&nbsp; &nbsp; ...

MYYA

为了简化您的代码,我建议使用fmt.Scanf如下所示:package mainimport "fmt"func main() {&nbsp; &nbsp; var animal, action string&nbsp; &nbsp; fmt.Printf("Enter animal: ")&nbsp; &nbsp; fmt.Scanf("%s", &animal)&nbsp; &nbsp; fmt.Printf("Enter action: ")&nbsp; &nbsp; fmt.Scanf("%s", &action)&nbsp; &nbsp; fmt.Printf("Animal was %s and action was %s", animal, action)}也不确定为什么会有多个反对票。是代码编写方式的问题吗?如果有人只是想学习语言,我认为没关系。首先让它工作,然后专注于其他事情。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go