当年龄不在范围之间时,抛出用户定义的异常

Sha*_*ikh 0 java constructor if-statement exception-handling try-catch

我创建了一个class Studentwith属性:rno, age, name, course我已经定义了一个参数化的构造函数.我想age在15到21之间抛出一个异常.我已经初始化age为27但是它没有进入if条件.你知道为什么会这样吗?

   class Age extends Exception
   {
   Age(String str)
   {
    super(str);
   }
  }

  public class Student
  {
   int rno,age;
   String name,course;

   Student(int r,int a,String n,String c) 
   { 
    rno=r;
    age=a;
    name=n;
    course=c;
   }

   public void display()
   { 
    try
      {
       if(age<=15 && age>=21)
          throw new Age("Not accepted");
       else 
        System.out.println("Name:"+name);
        System.out.println("Rno:"+rno);
        System.out.println("Age:"+age);
        System.out.println("Course:"+course);
        System.out.println("...........");
      }

   catch(Age a)
    {
       System.out.println(""+a);
    }
   }

   public static void main(String args[])
   {
    Student s1=new Student(1,26,"ABC","Java");
    Student s2=new Student(2,17,"XYZ","C++");
    s1.display();
    s2.display();
   }
  }

  Output
   Name:ABC
  Rno:1
  Age:26
  Course:Java
  ...........
  Name:XYZ
  Rno:2
  Age:17
  Course:C++
  ...........
Run Code Online (Sandbox Code Playgroud)

Bye*_*Bye 5

问题在于陈述if(age<=15 && age>=21)- 年龄永远不会低于15且大于21.

你有&&什么意思和在bool逻辑中,你需要将它改为||OR意味着.