如何阻止用户在Golang中继续执行。

huangapple go评论71阅读模式
英文:

How to stop users to continue in golang

问题

我可以帮你翻译代码部分。以下是翻译好的代码:

package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
	"strings"
)

func main() {

	fmt.Println("请在1到5之间为我们的披萨评分")

	reader := bufio.NewReader(os.Stdin)
	input, _ := reader.ReadString('\n')

	fmt.Println("您的评分是:", input)
	convertedInput, err := strconv.ParseFloat(strings.TrimSpace(input), 64)

	if convertedInput > 5 || convertedInput < 1 {
		fmt.Println("您应该在1到5之间评分")

		// 在这里停止程序

	} else {
		fmt.Println(convertedInput)
	}

	if err != nil {
		fmt.Println(err)
	} else {
		fmt.Println("您的评分是:", convertedInput)
	}

}

希望对你有帮助!

英文:

I want to prevent users if entering number Greater than 5 and less than 1

how can I do that?

package main

import (
	&quot;bufio&quot;
	&quot;fmt&quot;
	&quot;os&quot;
	&quot;strconv&quot;
	&quot;strings&quot;
)

func main()  {

	fmt.Println(&quot;Please rate our pizza between 1 and 5&quot;)

	reader := bufio.NewReader(os.Stdin)
	input, _ := reader.ReadString(&#39;\n&#39;)

	fmt.Println(&quot;Yourr rate is: &quot;, input)
	convertedInput, err := strconv.ParseFloat(strings.TrimSpace(input), 64)

	if convertedInput &gt; 5 || convertedInput &lt; 1 {
		fmt.Println(&quot;you should rate between 1 to 5&quot;)

		####want to stop program here

	}else {
	    fmt.Println(convertedInput)
	}

	if err != nil {
		fmt.Println(err)
	}else {
		fmt.Println(&quot;your rate is: &quot;, convertedInput)
	}
	
}

答案1

得分: 0

你可以从main函数中使用return语句来停止程序的执行。

    if convertedInput > 5 || convertedInput < 1 {
        fmt.Println("你应该给出1到5之间的评分")
        return
    }

或者,如果你想返回一个非零的退出码来指示错误,你可以使用os.Exit。这可能适合你,因为程序没有成功。

import (
    ...
    "os"
)
...

    if convertedInput > 5 || convertedInput < 1 {
        fmt.Println("你应该给出1到5之间的评分")
        os.Exit(1)
    }

最后,你可以使用panic来导致程序崩溃并输出堆栈跟踪。但是,在这种情况下,这不是合适的做法,因为这是用户输入错误,而不是需要通过堆栈跟踪进行调试的编程错误。但是,它确实会结束程序的执行。

也许你更希望反复询问用户,直到他们提供有效的答案。为此,你可以使用for循环。以下是一种方法:

func main()  {

    for {
        fmt.Println("请给我们的披萨评分(1到5)")

        input, _ := reader.ReadString('\n')

        fmt.Println("你的评分是:", input)
        convertedInput, err := strconv.ParseFloat(strings.TrimSpace(input), 64)
        if convertedInput > 5 || convertedInput < 1 {
            fmt.Println("你应该给出1到5之间的评分")
            continue
        }
        fmt.Println(convertedInput)

        if err != nil {
            fmt.Println(err)
        } else {
            fmt.Println("你的评分是:", convertedInput)
        }
        break
    }
    
}

仔细看一下这段代码,

input, _ := reader.ReadString('\n')

我建议不要忽略任何错误。你不知道这里的input是什么。在playground上尝试一下这段代码,看看它会导致什么意外行为。

还有这里:

    convertedInput, err := strconv.ParseFloat(strings.TrimSpace(input), 64)

    if convertedInput > 5 || convertedInput < 1 {
        fmt.Println("你应该给出1到5之间的评分")

        ####想在这里停止程序

    }else {
        fmt.Println(convertedInput)
    }

    if err != nil {
        fmt.Println(err)
    }else {
        fmt.Println("你的评分是:", convertedInput)
    }

这些条件的顺序有点奇怪。你在检查相关的err之前检查了convertedInput。我会这样做:

    if convertedInput, err := strconv.ParseFloat(strings.TrimSpace(input), 64); err != nil {
        fmt.Println("将输入转换为浮点数时出错:", err.Error())
    } else if convertedInput > 5 || convertedInput < 1 {
        fmt.Println("你应该给出1到5之间的评分")
        ## 进行结束/循环操作
    } else {
        fmt.Println("你的评分是:", convertedInput)
    }

这样,只有在ParseFloat成功后才会检查convertedInput

最后,

英文:

You can return from the main function to stop program execution.

    if convertedInput &gt; 5 || convertedInput &lt; 1 {
        fmt.Println(&quot;you should rate between 1 to 5&quot;)
        return
    }

Or, if you want to return a nonzero exit code to indicate error, you can use os.Exit. this is probably appropriate for you since the program did not succeed.

import (
 ....
 &quot;os&quot;
)
...

    if convertedInput &gt; 5 || convertedInput &lt; 1 {
        fmt.Println(&quot;you should rate between 1 to 5&quot;)
        os.Exit(1)
    }

Finally, you could panic which would dump a stack trace. That wouldn't be appropriate for this case as it's an error with user input, not a programming error you'd debug with a stack trace. But it will end the program.

Maybe instead you'd prefer to ask the user repeatedly until they provide a valid answer. For this, use a for loop. This is one way:

func main()  {

	for {
		fmt.Println(&quot;Please rate our pizza between 1 and 5&quot;)

		input, _ := reader.ReadString(&#39;\n&#39;)

		fmt.Println(&quot;Yourr rate is: &quot;, input)
		convertedInput, err := strconv.ParseFloat(strings.TrimSpace(input), 64)
		if convertedInput &gt; 5 || convertedInput &lt; 1 {
			fmt.Println(&quot;you should rate between 1 to 5&quot;)
			continue
		}
		fmt.Println(convertedInput)

		if err != nil {
			fmt.Println(err)
		} else {
			fmt.Println(&quot;your rate is: &quot;, convertedInput)
		}
		break
	}
    
}

Looking back at this code in more detail,

input, _ := reader.ReadString(&#39;\n&#39;)

I recommend against ever ignoring errors. You don't know what input is here. Try the code on the playground to see how that causes unexpected behavior.

And down here:

    convertedInput, err := strconv.ParseFloat(strings.TrimSpace(input), 64)

    if convertedInput &gt; 5 || convertedInput &lt; 1 {
        fmt.Println(&quot;you should rate between 1 to 5&quot;)

        ####want to stop program here

    }else {
        fmt.Println(convertedInput)
    }

    if err != nil {
        fmt.Println(err)
    }else {
        fmt.Println(&quot;your rate is: &quot;, convertedInput)
    }

These conditions are in a funny order. You check convertedInput before you check the associated err. I would do it like this:

    if convertedInput, err := strconv.ParseFloat(strings.TrimSpace(input), 64); err != nil {
        fmt.Println(&quot;Error converting input to Float: %s&quot;, err.Error())
    } else if convertedInput &gt; 5 || convertedInput &lt; 1 {
        fmt.Println(&quot;you should rate between 1 to 5&quot;)
        ## Do whatever ending / looping
    }else {
        fmt.Println(&quot;your rate is: &quot;, convertedInput)
    }

That way you're only checking convertedInput if ParseFloat succeeded.

Finally,

huangapple
  • 本文由 发表于 2023年5月5日 00:16:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/76175297.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定