while ture try

编程入门 行业动态 更新时间:2024-10-23 15:17:41

while <a href=https://www.elefans.com/category/jswz/34/1703255.html style=ture try"/>

while ture try

age = int(input("请输入你家狗狗的年龄: "))
print("")
if age < 0:print("你是在逗我吧!")
elif age == 1:print("相当于 14 岁的人。")
elif age == 2:print("相当于 22 岁的人。")
elif age > 2:human = 22 + (age -2)*5print("对应人类年龄: ", human)### 退出提示
input("点击 enter 键退出")
print("=======欢迎进入狗狗年龄对比系统========")
while True:try:age = int(input("请输入您家狗的年龄:"))print(" ")age = float(age)if age < 0:print("您在逗我?")elif age == 1:print("相当于人类14岁")breakelif age == 2:print("相当于人类22岁")breakelse:human = 22 + (age - 2)*5print("相当于人类:",human)breakexcept valueerror:print("输入不合法,请输入有效年龄")
#退出提示
input("点击 enter 键退出") 

有点弄不懂while ture try -except,查了查,参考别人的资料:


try语句按照如下方式工作;
首先,执行try子句(在关键字try和关键字except之间的语句)
如果没有异常发生,忽略except子句,try子句执行后结束。
如果在执行try子句的过程中发生了异常,那么try子句余下的部分将被忽略。如果异常的类型和 except 之后的名称相符,那么对应的except子句将被执行。最后执行 try 语句之后的代码。
如果一个异常没有与任何的except匹配,那么这个异常将会传递给上层的try中。
一个 try 语句可能包含多个except子句,分别来处理不同的特定的异常。最多只有一个分支会被执行。
处理程序将只针对对应的try子句中的异常进行处理,而不是其他的 try 的处理程序中的异常。


if-else场景

if fun():do something1
else:do something2

如果fun()抛出异常表示假,那么可以改写成如下形式

try:fun()do something1
expect:do something2

类似的while场景

while fun():do something

如果fun()抛出异常表示假,那么可以改写成如下形式

while True:try:fun()breakexpect:do something

在JAVA中,我也找到了相关的表达方式:
目标:判断用户输入的数据是否是数字,如果不是,提示用户重新输入,使用while true循环实现

问题:当输入第一个数据是字符时,catch块捕获到异常执行完catch块后循环输出
“输入的内容包含非数字的字符,请重新输入”

原因:Scanner声明在while循环外,当第一次出现异常后没有清空Scanner中的数据,

解决方法:将Scanner写到循环内声明

package com;import java.util.Scanner;public class ExceptionDemo1 {public static void main(String[] args) {int a=0;int b=0;Scanner sc=new Scanner(System.in);//这里出问题了,声明写到循环内while(true){try {
//              Scanner sc=new Scanner(System.in);System.out.println("请输入被除数");a=sc.nextInt();System.out.println("请输入除数");b=sc.nextInt();} catch (Exception e) {System.out.println("输入的内容包含非数字的字符,请重新输入");}try {System.out.println("商是"+(a/b));} catch (Exception e) {System.out.println("NaN");}}}}

更多推荐

while ture try

本文发布于:2024-02-26 17:01:31,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1703252.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:ture

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!