gpt4 book ai didi

string - 我的指数超出范围,我开始 panic ,我无法摆脱

转载 作者:行者123 更新时间:2023-12-01 22:45:35 25 4
gpt4 key购买 nike

关闭。这个问题不符合Stack Overflow guidelines .它目前不接受答案。












想改进这个问题?将问题更新为 on-topic对于堆栈溢出。

1年前关闭。




Improve this question




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

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

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

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

两个问题:
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]

...

关于string - 我的指数超出范围,我开始 panic ,我无法摆脱,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62077176/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com