黑马程序员技术交流社区

标题: 一个关于判断的问题,,,求指点... [打印本页]

作者: 伍艳雄    时间: 2014-1-1 17:21
标题: 一个关于判断的问题,,,求指点...
本帖最后由 伍艳雄 于 2014-1-1 17:37 编辑
  1. class Preson {
  2.         private int age;
  3.         private int score;
  4.         Preson(int age,int score) {
  5.                 if (this.age>0&&this.age<130) {
  6.                         this.age=age;
  7.                         System.out.println("age="+age);
  8.                 }else {
  9.                         System.out.println("nono..");
  10.                 }

  11.                 if (this.score>=0&&this.score<=150) {
  12.                         this.score=score;
  13.                         System.out.println("score="+score);
  14.                 }else {
  15.                         System.out.println("nononono.");
  16.                 }
  17.         }
  18. }
  19. class Test11 {
  20.         public static void main(String[] args) {
  21.                 new Preson(-20,-90);//当我输入两个负数时,应该全是no,,,,,,但结果age可以判断,但score就直接打出负数了,..这怎么解决
  22.         }
  23. }
复制代码
怎么只判断第一个,而第二个直接打印了


作者: daoyua    时间: 2014-1-1 17:29
错误给你找到了,第二个判断改成if (score>=0&&score<=150)就行了,原因我还在看
作者: 伍艳雄    时间: 2014-1-1 17:31
daoyua 发表于 2014-1-1 17:29
错误给你找到了,第二个判断改成if (score>=0&&score

你的意思是this在做怪???....为何第一个可以???
作者: daoyua    时间: 2014-1-1 17:32
知道你错误了,第二个判断this.score默认为0的,符合判断的,你为什么用this嘛,直接score就行了
作者: daoyua    时间: 2014-1-1 17:33
解决了,可以关闭啦
作者: 伍艳雄    时间: 2014-1-1 17:36
daoyua 发表于 2014-1-1 17:32
知道你错误了,第二个判断this.score默认为0的,符合判断的,你为什么用this嘛,直接score就行了 ...

    好吧...谢谢你帮我找出了错误
作者: daoyua    时间: 2014-1-1 17:42
新建的int参数,默认值是为0的
作者: sd110572    时间: 2014-1-1 17:47
你的 this.age=age; 和   this.score=score;是先判定在再赋值的。
在2个if判断之前你的成员变量score和age都是初始值0,所以要去掉this,
用你传的形参来判断,至于形参去看书百度。
作者: taoge    时间: 2014-1-3 15:34
  1. class Preson {
  2.     private int age;
  3.     private int score;
  4.     Preson(int age,int score) {
  5.             if (this.age>0&&this.age<130) {
  6.                     this.age=age;
  7.                     System.out.println("age="+age);
  8.             }else {
  9.                     System.out.println("nono..");
  10.             }

  11.             if (this.score>0&&this.score<150) { //把这里的>=,<=改成>,<就是你想要的答案了,this.score指的是成员变量private int score,初始值为0,你写>=0当然满足条件了
  12.                     this.score=score;                       
  13.                     System.out.println("score="+score);
  14.             }else {
  15.                     System.out.println("nononono.");
  16.             }
  17.     }
  18. }
  19. class Test11 {
  20.     public static void main(String[] args) {
  21.             new Preson(-20,-90);
  22.     }
  23. }
复制代码





欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2