为什么输入不合法,程序还是继续执行下面的代码?

yywu2000 2021-04-15 02:24:38
请教各位大神,为什么在setter里设置了年龄必须在0-100之间,但是即使输入了错误的数字,程序还是一直执行到底?


class getter {
private String name;
private int age;

public String getName() {
return this.name;
}

public void setName(String name) {
this.name = name;
}

public int getAge() {
return this.age;
}

public void setAge(int age) {
if(age>0&&age<100){
this.age = age;
}else {
System.out.println("输入不合法,请重新输入!");
return;
}
}
}
——————————————————————————————
import java.util.Scanner;

public class test {
public static void main(String[] args) {
getter g = new getter();
Scanner sc = new Scanner(System.in);
System.out.println("请输入姓名:");
String s1 = sc.nextLine();
g.setName(s1);
System.out.println("请输入年龄:");
int s2 = sc.nextInt();
g.setAge(s2);
System.out.println(g.getName());
System.out.println(g.getAge());
System.out.println("我叫"+g.getName()+","+"我今年"+g.getAge()+"岁");
}
}
...全文
225 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
老紫竹 2021-04-20
  • 打赏
  • 举报
回复
引用 5 楼 NLimit 的回复:
set方法里面抛出一个异常,在main方法里面捕获这个异常
这个靠谱, 比如throws new Exception("setAge ,数值未..... 输入不合法,请重新输入!");
yywu2000 2021-04-20
  • 打赏
  • 举报
回复
谢谢!!!!
NLimit 2021-04-18
  • 打赏
  • 举报
回复
set方法里面抛出一个异常,在main方法里面捕获这个异常
yywu2000 2021-04-15
  • 打赏
  • 举报
回复
ide确实提示return不必要,如果输入错误需要终止运行并等待重新输入,要怎么做呢?谢谢!
立青_ 2021-04-15
  • 打赏
  • 举报
回复
如果你的ide足够智能,它会提示你 'return' 不必要,因为是 'void' 方法中的最后一条语句
立青_ 2021-04-15
  • 打赏
  • 举报
回复
return只是结束当前方法,也就是setAge方法,main还在继续执行啊
  • 打赏
  • 举报
回复
只是打印了那句话而已,并没有中断程序。

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧