登录
首页 >  Golang >  Go问答

我因超出范围索引而陷入恐慌,却束手无策

来源:stackoverflow

时间:2024-02-28 21:48:24 456浏览 收藏

大家好,今天本人给大家带来文章《我因超出范围索引而陷入恐慌,却束手无策》,文中内容主要涉及到,如果你对Golang方面的知识点感兴趣,那就请各位朋友继续看下去吧~希望能真正帮到你们,谢谢!

问题内容

我编写这个程序是为了熟悉类型(而不是对象!)。

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

因此,用户条目应该位于用“”分隔的一行上。我使用 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)

            case "bird": 
                bird.info(infoe)
            default: 
                fmt.Println("I don't know about that animal.")          
            }
        } else {
            fmt.Printf("I don't have that informtion")
                break
            }
        }
    }

解决方案


在循环外部创建扫描器以避免丢弃缓冲数据。当 scan() 返回 false 时中断。检查并处理无效输入。

scanner := bufio.newscanner(os.stdin)
for {
    fmt.println("remember enter x to exit")
    if !scanner.scan() {
        break
    }
    request := scanner.text()
    parts := strings.split(request, " ")
    if parts[0] == "x" {
        break
    }
    if len(parts) < 2 {
        fmt.println("bad input")
        break
    }

    typed := parts[0]
    infoe := parts[1]

    ...

为了简化您的代码,我建议使用 fmt.scanf ,如下所示:

package main

import "fmt"

func main() {
    var animal, action string

    fmt.Printf("Enter animal: ")
    fmt.Scanf("%s", &animal)
    fmt.Printf("Enter action: ")
    fmt.Scanf("%s", &action)

    fmt.Printf("Animal was %s and action was %s", animal, action)
}

我也不确定为什么有多个反对票。是不是代码写法的问题?我认为如果有人只是想学习这门语言那没关系。首先让它发挥作用,然后再专注于其他事情。

一旦您熟悉了该语言,您就可以完成 Effective Go 中列出的要点

以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于Golang的相关知识,也可关注golang学习网公众号。

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>