我已经从学习JS转到学习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]
...
• Kali 6.1.0 启动错误:Kali Purple 工具未显示?
• Swift/ContiguousArrayBuffer.swift:600: 致命错误:索引超出范围
• Python:使用带有 IndexError 的 LSTM 序列:列表分配索引超出范围
• 我在这里找不到解决方案list index out of range
• 如何修复(IndexError:列表索引超出范围)python 2 和 3? [关闭]
• 在给定数组中查找重复项 - 当我在 Scala 中执行 foldLeft 时,长度为 4 的索引 5 超出范围
• UICollectionView 在多个部分之间拖放单元格
• 是否存在您不想处理超出范围的 IDisposable 对象的情况?
• Fedora 37 更新后重启 - Grub 指针超出范围并且无法通过 USB 挽救启动
• How to set up framer-motion in React Router Dom with its RouterProvider?