0

This is the part of my codes which I want to use try-catch exception,Now how to use try and catch exception in this codes? Example if there is no enrolled students in case no.3(prog2) and case no.4(CSO), it displays NO ENROLLED students...

   switch(menu){
       case 1:
           System.out.println("******[1]Output******");
           sortNameSub(file1);
           for(int str=0;str<5;str++)
               System.out.println(file1[str]);
           System.out.print("Press [r] to return to main manu....");
           String r=copy.next();
           if("r".equals(r))
               break;
       case 2:
           System.out.println("*****[2]Output******");
           for(int x=0;x<5;x++){
               sortId(file2);
               for(int y=0;y<5;y++){
               if(Integer.parseInt(file[y][1])==file2[x])
                  System.out.println(file2[x]+";"+file[y][0]);
               }                
           }

           System.out.print("Press [r] to return to main manu....");
           r=copy.next();
           if("r".equals(r))
           break;
       case 3:
           System.out.println("******[3]Output*****");

           for(int x=0;x<5;x++){
             if(file[x][2].equalsIgnoreCase(prog2))
                 System.out.println(file[x][0]+";"+file[x][1]);
           }
           System.out.print("Press [r] to return to main manu....");
           r=copy.next();
           if("r".equals(r))
           break;
       case 4:
           System.out.println("******[4]Output******");
           for(int x=0;x<5;x++){
             if(file[x][2].equalsIgnoreCase(cso))
               System.out.println(file[x][0]+";"+file[x][1]);
           }
           System.out.print("Press [r] to return to main manu....");
           r=copy.next();
           if("r".equals(r))
           break;
       case 5:
           menu=5;
   }
   }while(menu!=5); 

1 Answers1

0

If I understand the question, then you don't need a try/catch here. Just use a counter to keep track of how many things have been printed. If counter is 0, print the message:

case 3:
    System.out.println("******[3]Output*****");

    int counter = 0;

    for(int x=0;x<5;x++){
        if(file[x][2].equalsIgnoreCase(prog2)) {
            System.out.println(file[x][0]+";"+file[x][1]);
            counter += 1;
        }
    }

    if (0 == counter) {
        System.out.println("NO ENROLLED students...");
    }

    System.out.print("Press [r] to return to main manu....");
    r=copy.next();
    if("r".equals(r))
    break;
001
  • 13,291
  • 5
  • 35
  • 66
  • No problem. If this answer helped you please mark it as accepted (click the check box to the left of the answer). – 001 May 16 '14 at 17:35