How to restrict the object of a class upto 10.If objects exceeds the limit though "LimitCrossed" Exception.plz rply code urgent.....
public class Arm { public static void main(String[] args) throws Exception { for (int k = 10; k <= 1000; k++) { int n = k; int d = 0; int s = 0; while (n > 0) { d = n % 10; s = s + (d * d * d); n = n / 10; } if (k == s) { System.out.println(k + " is Armstrong number"); } } } }
OutPut:
153 is Armstrong number 370 is Armstrong number 371 is Armstrong number 407 is Armstrong number
hi, Here I am giving a code which will restrict the object creation upto a fix number of times. And this will throw an exception if the object creation of a class is exceeded a fix number of times.
Here I am giving a sample code for detail visit the following url http://www.roseindia.net/java/limitclassobjectcreation.shtml
ClassInstance.java
import java.util.ArrayList; import java.util.List; import java.util.ListIterator; public final class ClassInstance { private static ClassInstance ci; private static int counter=0; private ClassInstance() { counter++; } public static ClassInstance getClassInstance() { if(counter<5) { ci = new ClassInstance(); } else if(counter >=5) { ci = new ClassInstance(); ci=null; } return ci; } public static void main(String[] args) { try{ List<ClassInstance> list = new ArrayList<ClassInstance>(); ClassInstance obj1 = ClassInstance.getClassInstance(); ClassInstance obj2 = ClassInstance.getClassInstance(); ClassInstance obj3 = ClassInstance.getClassInstance(); ClassInstance obj4 = ClassInstance.getClassInstance(); ClassInstance obj5 = ClassInstance.getClassInstance(); ClassInstance obj6 = ClassInstance.getClassInstance(); ClassInstance obj7 = ClassInstance.getClassInstance(); ClassInstance obj8 = ClassInstance.getClassInstance(); list.add(obj1); list.add(obj2); list.add(obj3); list.add(obj4); list.add(obj5); list.add(obj6); list.add(obj7); list.add(obj8); ListIterator<ClassInstance> itr = list.listIterator(); while(itr.hasNext()) { System.out.println(itr.next().hashCode()); } } catch(Exception e) { try { if(counter >= 5) { MyException.counter = counter; } throw new MyException(); } catch(MyException e1) { System.out.println("Exception@ "+ClassInstance.class+" : "+e1); } } } }
Ads