【发布时间】:2020-07-23 00:41:22
【问题描述】:
我想让“for 循环”循环 3 次或直到用户输入除整数以外的其他内容。下面是我的代码,尽管它运行了无数次并打印出用户输入的第一个值。
package main
import "fmt"
import "bufio"
import "strconv"
import "os"
import "sort"
func main(){
emptySlice := make([]int, 3) // Capacity of 3
fmt.Println(cap(emptySlice))
scanner := bufio.NewScanner(os.Stdin) // Creating scanner object
fmt.Printf("Please enter a number: ")
scanner.Scan() // Will always scan in a string regardless if its a number
for i := 0; i < cap(emptySlice); i++ { // Should this not run 3 times?
input, err := strconv.ParseInt(scanner.Text(), 10, 16)
if err != nil{
fmt.Println("Not a valid entry! Ending program")
break
}
emptySlice = append(emptySlice, int(input)) // adds input to the slice
sort.Ints(emptySlice) // sorts the slice
fmt.Println(emptySlice) // Prints the slice
}
}
【问题讨论】:
-
emptySlice = append(...)-- 这没有意义。如果您附加到切片,则切片不再为空。 -
@MarkusWMahlberg 这可能是链接softwareengineering.meta.stackexchange.com/questions/6166/…
标签: for-loop go infinite-loop