R语言else语句中paste0未打印消息问题排查
问题描述
我输入非1、2、3、4的整数时,代码进入了else语句,但没有打印出paste0生成的提示文本,也没报错,请问问题出在哪里?
原代码如下:
escolha <- as.integer(readline(prompt="Enter your choice: ")) if(escolha == 1){ print("Cool you choose addition!") } else if (escolha == 2) { print("Cool, you choose subtraction!") } else if (escolha == 3) { print("Cool, you choose multiplication!") } else if (escolha == 4){ print("Cool, you choose division!") } else{ paste0("It's not possible to use ", escolha," as input.") escolha<- as.integer(readline(prompt="Choose a valid number (1 a 4): ")) } num1 <- as.double(readline(prompt="What is the first number? ")) num2 <- as.double(readline(prompt="What is the second number? ")) resultado <- switch (escolha, (num1+num2), (num1-num2), (num1*num2), (num1/num2)) cat("The result is: ", resultado)
问题原因
paste0生成的文本未输出:你仅调用paste0生成了字符串,但没有用print()或cat()将其输出到控制台,所以这段文本只会存在于内存中,不会显示给用户。- 输入校验逻辑有漏洞:当前else语句只处理一次重新输入,若用户再次输入无效数字,代码会直接跳过提示环节,进入后续的数字输入步骤,无法确保输入有效性。
修复后的代码
# 循环校验输入,直到用户输入有效数字 repeat { escolha <- as.integer(readline(prompt="Enter your choice: ")) if(escolha == 1){ print("Cool you choose addition!") break } else if (escolha == 2) { print("Cool, you choose subtraction!") break } else if (escolha == 3) { print("Cool, you choose multiplication!") break } else if (escolha == 4){ print("Cool, you choose division!") break } else{ # 用cat输出提示文本,换行符\n让提示更清晰 cat(paste0("It's not possible to use ", escolha," as input.\n")) } } num1 <- as.double(readline(prompt="What is the first number? ")) num2 <- as.double(readline(prompt="What is the second number? ")) resultado <- switch (escolha, (num1+num2), (num1-num2), (num1*num2), (num1/num2)) cat("The result is: ", resultado)
关键修复点
- 给
paste0的结果添加cat()(或print()),确保提示文本能显示在控制台。 - 用
repeat循环包裹输入校验逻辑,强制用户必须输入1-4的有效数字才会进入后续步骤,彻底避免无效输入直接跳过的问题。
内容的提问来源于stack exchange,提问作者gabrielleAmbrosio
相关产品推荐
相关产品推荐

