Sei sulla pagina 1di 17

Miguel Kabigting

IT 26

September 11, 2020

Ms. Raychelou Valencia

IT 26 – Lab Exercise: Exception and Assertion

I). Java Lab Exercise on Exception and Assertion


1. Arabic to Roman Numeral Converter -> Roman Numeral to Arabic Converter

Program code:

Main class(run):

package num1;
import java.util.*;
import num1.Numbers.ArabicToRoman;

public class Num1 {  
public static void main(String[] arg){
 try{   
     
ToFourThousand number = new ToFourThousand();

    System.out.println("Arabic Numeral to Roman Numeral Converter");
    System.out.println(" ");
    System.out.print("Please input your Arabic number from 1-3999 to
convert: ");

    Scanner scan = new Scanner(System.in);
    int input = scan.nextInt();
    
    System.out.print("The Roman Numeral conversion is: ");
    number.input(input);
    System.out.println(" ");

    }
 
 catch(InputMismatchException e){
   System.out.println("InputMismatchException: Invalid. Your inputted number sho
uld ranging from 1-3999");  
 }
  } 
}
ArabicToRoman class:

package num1.Numbers;

import java.util.InputMismatchException;

public class ArabicToRoman {
public ArabicToRoman(){};

String[] oneNine = new String[] { "", "I", "II", "III", "IV", "V", "VI", "VII", 
"VIII", "IX"};

String[] tenHundred = new String[] { "X", "XX", "XXX", "XL", "L", "LX", "LXX", "
LXXX", "XC"};

String[] hundredThousand = new String[] { "C", "CC", "CCC", "CD", "D", "DC", "DC
C", "DCCC", "CM"};

String[] thousands = new String[] { "M", "MM", "MMM" };

public void input(int input){
if(input < 1 || input >= 4000){
   System.out.println("InputMismatchException: It must be an arabic number rangi
ng from 1-3999");  
 }

int fstNumber = 0;
int sndNumber = 0;
int trdNumber = 0;

int fthNumber=0;
if(input / 1000 == 1)
fthNumber = 0;
else if(input / 1000 == 2)
fthNumber = 1;
else if(input / 1000 == 3)
fthNumber = 2;

if(input % 10 == input)
fstNumber = input;
else if(input % 100 == input)
fstNumber = input%10;
else if(input % 1000 == input)
fstNumber = (input%100)%10;
else if(input % 1000 <= input)
fstNumber = ((input%1000)%100)%10;

if(input % 1000 == input)
if(input % 100 == input)
sndNumber = input/10;
else
sndNumber = (input%100)/10;
else
sndNumber = ((input%1000)%100)/10;

if(input % 1000 == input)
trdNumber = input/100;
else
trdNumber = (input%1000)/100;

String[] number = new String[4];

if(input % 1000 == 0 || input % 1000 < input)
number[0] = thousands[fthNumber];
else if(input % 1000 == input)
number[0] = "";

if(input % 1000 < 1000 && (input%1000)<100)
number[1] = "";
else if(input%1000 == input || (input % 1000 < 1000 && input % 1000 >= 100))
number[1] = hundredThousand[trdNumber - 1];

if((input % 1000 < input && (input%1000)%100 >= 10) || (input%1000 == input && 
input%100 >= 10))
number[2] = tenHundred[sndNumber - 1];
else
number[2] = "";

number[3] = oneNine[fstNumber];

for (String currentNumber : number){
if("".equals(currentNumber))
continue;

System.out.print(currentNumber);

        }
    }
}
Output:

Arabic Numeral to Roman Numeral Converter

Please input your Arabic number from 1-3999 to convert: 1998

The Roman Numeral conversion is: MCMXCVIII

1. Arabic Numbers to word converter


Source Code:

ArabicToWords(run) source code:

public class ArabicToWords extends ArabicToWordsTest{
 public static void main(String[] args)
    {
        System.out.println("Arabic Numeral to Words Converter");
        System.out.println(" ");
        ArabicToWordsTest x = new ArabicToWordsTest();
        x.inputNumber();
        System.out.println("Input in Words : " + x.convertNumberToWords(num));
    }
}

ArabicToWordsTest source code:

import java.util.*;
public class ArabicToWordsTest {
    private static String input;
    static int num;
    private static String[] units = {""," One"," Two"," Three"," Four"," Five"," 
Six"," Seven"," Eight"," Nine"};
    private static String[] teen = {" Ten"," Eleven"," Twelve"," Thirteen"," Fou
rteen"," Fifteen"," Sixteen"," Seventeen"," Eighteen"," Nineteen"};
    private static String[] tens = { " Twenty"," Thirty"," Forty"," Fifty"," Six
ty"," Seventy"," Eighty"," Ninety"};
    private static String[] maxs = {"",""," Hundred"," Thousand"," Lakh"," Crore
"};
    
 
    public String convertNumberToWords(int n){
        input = numToString(n);
        String converted = ""; 
        int pos = 1; 
        boolean hun = false;
        
        while(input.length() > 0){
            
            if(pos == 1) {   
                if(input.length() >= 2) {   
                 String temp = input.substring(input.length() - 2,input.length()
);
                 input = input.substring(0,input.length() - 2);
                 converted += digits(temp);
                }
                else if(input.length() == 1) {
                 converted += digits(input); 
                 input = "";
                }
                pos++;
            }
            
            else if(pos == 2) { 
                String temp = input.substring(input.length()-1,input.length());
                input = input.substring(0,input.length()-1);
                
                if(converted.length() > 0 && digits(temp) != ""){
                    converted = (digits(temp) + maxs[pos] + " ") + converted;
                    hun = true;
                }
                else{
                    if
                    (digits(temp) == "");
                    else
                    converted = (digits(temp) + maxs[pos]) + converted;
                    hun = true;
                }
                pos++;
            }
            else if(pos > 2) {
                if(input.length() >= 2) {  
                 String temp = input.substring(input.length() - 2,input.length()
);
                 input = input.substring(0,input.length() - 2);
                 
                   if(!hun&&converted.length()> 0)
                        converted = digits(temp)+maxs[pos] + " " + converted;
                   
                    else{
                       
                        if(digits(temp) == "");
                        
                        else
                        converted = digits(temp) + maxs[pos] + converted;
                        
                    }
                 }
                
                 else if(input.length() == 1) {
                     
                   if(!hun&&converted.length() > 0)
                    converted = digits(input) + maxs[pos] + " " + converted;
                   
                    else{
                        if(digits(input) == "")  ;
                        else
                        converted = digits(input) + maxs[pos] + converted;
                        input = "";
                    }
                 }
                 pos++; 
             }
        }
        return converted;
    }
    
    private String digits(String temp) {
        String converted="";
        for(int i = temp.length() - 1; i >= 0; i--){   
            int ch = temp.charAt(i)-48;
            if(i == 0 && ch > 1 && temp.length() > 1)
            converted = tens[ch - 2] + converted; 
            else if(i == 0 && ch == 1 && temp.length() == 2) {
                int sum = 0;
                for(int j = 0; j < 2; j++)
                sum = (sum * 10) + (temp.charAt(j) - 48);
                return teen[sum - 10];
            }
            else{
                if(ch > 0)
                converted=units[ch] + converted;
            } 
        }
        return converted;
    }
    private String numToString(int x) {
        String num = "";
        while(x != 0){
            num=((char)((x % 10) + 48))+num;
            x /= 10;
        }
        return num;
    }
    void inputNumber(){
        
        Scanner in = new Scanner(System.in);
        try{
          System.out.print("Please input your Arabic Numerals to convert: ");
          num = in.nextInt();
          
          if(num < 1 || num >= 4000){
          System.out.println("InputMismatchException: Invalid. It must be an ara
bic number ranging from 1-3999");  
    }
        }
        catch(InputMismatchException e) {
          System.out.println("InputMismatchException: Invalid. It must be an ara
bic number ranging from 1-3999");
          System.exit(1);
        }
    }
  
}

Output:
3. Create a Class FindArray that will try to iterate in the array displaying the content in
each index. The program should be able to catch an
ArrayIndexOutOfBoundsException, a NullPointerException and a RunTimeException.

Source code:

import java.util.*;
public class FindArray {

    public static void main(String[] args) {
     try{
         char[] matrix = new char[] {'M', 'E', 'L', 'L', 'O', 'W', 'D', 'R', 'A'
, 'M', 'A'};
         System.out.println("M E L L O W D R A M A ");
         System.out.println("Please enter the index of the element to display: "
);
         
         Scanner scan = new Scanner(System.in);
         int size = scan.nextInt();
         

         System.out.println(matrix[size]);     
          
     }
      catch(ArrayIndexOutOfBoundsException e){
         System.out.println("  ");
         System.out.println ("ArrayIndexOutOfBoundsException: Array Index is out 
of bounds.");
      }
     
      catch(NullPointerException e){
         System.out.println ("NullPointerException: Cannot access a null object, 
please assign a value first.");
      }

     catch(RuntimeException e){
         System.out.println ("RuntimeException: It must be an integer.");
         
     }
     
     
    } 
}
Output:

4. Create a program that will ask the user a string input and will then try return the
string in backward order, the program should be able to catch a
StringIndexOutOfBoundsExeption.

Source code:

import java.util.*;
public class Backward {

    public static void main(String[] args) {
     try{
     
         String original = "ALEX L. PORTIS"; 
         String str1 = original.substring(5); 

         String reverse = ""; 
 
      System.out.print("Please enter a string to reverse: ");
      
        Scanner scan3 = new Scanner(System.in);
        original = scan3.nextLine();
        
      int length = original.length();
      
          for ( int i = length - 1 ; i >= 0 ; i-- ){
         reverse = reverse + original.charAt(i);
          }  
      
      System.out.println("The Reverse of entered string is: " + reverse);        
     
     }
      catch(StringIndexOutOfBoundsException e){
         System.out.println("  ");
         System.out.println ("StringIndexOutOfBoundsExeption: String Index Out O
f Bounds.");
      }
    }    
}
Output:

5. Implement a class called Birthday that extends the MyDate class. Include 2
constructors, one with month, day and year parameters and another one with only
month and day as parameters. The second constructor will call the parent
constructor passing the default value1970 for the year. Implement an inner class
InvalidDateException that extends the Exception class. The message in the exception
should read “Invalid Date!” Include a method called String
getZodiacSign() throws InvalidDate Exception that returns the zodiac sign of the
person if it valid and throws an exception if not valid.

Use the table below:


Aquarius Jan 20 – Feb 18
Pisces Feb 19 – Mar 20
Aries Mar 21 – Apr 19
Taurus Apr 20 – May 20
Gemini May 21 – Jun 20
Cancer Jun 21 – Jul 22
Leo Jul 23 – Aug 22

Virgo Aug 23 – Sep 22

Libra Sep 23 – Oct 22

Scorpio Oct 23 – Nov 21


Sagittarius Nov 22 – Dec 21
Capricorn Dec 22 – Jan 19

Source code:

import java.util.*;
public class ZodiacSign {

    public static void main(String[] args) {
     try{ 
       
        int month, day, sign;
        
        int choice;
        
        System.out.print("Know your Zodiac Sign");
        System.out.println("   ");
        
        System.out.println("1.  January");
        System.out.println("2.  February");
        System.out.println("3.  March");
        System.out.println("4.  April");
        System.out.println("5.  May");
        System.out.println("6.  June");
        System.out.println("7.  July");
        System.out.println("8.  August");
        System.out.println("9.  September");
        System.out.println("10. October");
        System.out.println("11. November");
        System.out.println("12. December");
        
        System.out.println("   ");
        
        System.out.print("Please enter your month of birth: ");
        Scanner scannn = new Scanner(System.in);
        choice = scannn.nextInt();
     
        switch(choice){
                
            case 1:
                System.out.print("Enter day: ");
                Scanner scan1 = new Scanner(System.in);
                day = scan1.nextInt();
                
                if(day > 31){
                System.out.println("Invalid date! Please try again");
                }
                
                else{
                if(day >= 20)
                    System.out.print("The Zodiac sign for January " + day + " is 
Aquarius.");
                else if(day < 20)
                    System.out.print("The Zodiac sign for January " + day + " is 
Capricorn.");
                }
            break;
                
                
            case 2:
                System.out.print("Enter day: ");
                Scanner scan2 = new Scanner(System.in);
                day = scan2.nextInt();
                if(day > 29){
                    System.out.println("Invalid date! Please try again");
                }
                else{
                if(day >= 19)
                    System.out.print("The Zodiac sign for Februray " + day + " i
s Pisces.");
                else if(day < 19)
                    System.out.print("The Zodiac sign for February " + day + " i
s Aquarius.");
                }
            break;
                
                
            case 3:
                System.out.print("Enter day: ");
                Scanner scan3 = new Scanner(System.in);
                day = scan3.nextInt();
                if(day > 31){
                    System.out.println("Invalid date! Please try again");
                }
                else{
                if(day >= 21)
                    System.out.print("The Zodiac sign for March " + day + " is A
ries.");
                else if(day < 21)
                    System.out.print("The Zodiac sign for March " + day + " is P
isces.");
                }
            break;
                
                
            case 4:
                System.out.print("Enter day: ");
                Scanner scan4 = new Scanner(System.in);
                day = scan4.nextInt();
                if(day > 30){
                    System.out.println("Invalid date! Please try again");
                }
                else{
                if(day >= 20)
                    System.out.print("The Zodiac sign for April " + day + " is T
aurus.");
                else if(day < 20)
                    System.out.print("The Zodiac sign for April " + day + " is A
ries.");
                }
            break;
                
            
            case 5:
                System.out.print("Enter day: ");
                Scanner scan5 = new Scanner(System.in);
                day = scan5.nextInt();
                if(day > 31){
                    System.out.println("Invalid date! Please try again");
                }
                else{
                if(day >= 21)
                    System.out.print("The Zodiac sign for May " + day + " is Gem
ini.");
                else if(day < 21)
                    System.out.print("The Zodiac sign for May " + day + " is Tau
rus.");
                }
            break;
                
                
            case 6:
                System.out.print("Enter day: ");
                Scanner scan6 = new Scanner(System.in);
                day = scan6.nextInt();
                if(day > 30){
                    System.out.println("Invalid date! Please try again");
                }
                else{
                if(day >= 21)
                    System.out.print("The Zodiac sign for June " + day + " is Ca
ncer.");
                else if(day < 21)
                    System.out.print("The Zodiac sign for June " + day + " is Ge
mini.");
                }
            break;
                
                
            case 7:
                System.out.print("Enter day: ");
                Scanner scan7 = new Scanner(System.in);
                day = scan7.nextInt();
                if(day > 31){
                    System.out.println("Invalid date! Please try again");
                }
            else{
                if(day >= 23)
                    System.out.print("The Zodiac sign for July " + day + " is Le
o.");
                else if(day < 23)
                    System.out.print("The Zodiac sign for July " + day + " is Ca
ncer.");
            }
            break;
                
                
            case 8:
                System.out.print("Enter day: ");
                Scanner scan8 = new Scanner(System.in);
                day = scan8.nextInt();
                if(day > 31){
                    System.out.println("Invalid date! Please try again");
                }
            else{
                if(day >= 23)
                    System.out.print("The Zodiac sign for August " + day + " is 
Virgo.");
                else if(day < 23)
                    System.out.print("The Zodiac sign for August " + day + " is 
Leo.");
            }
            break;
                
                
            case 9:
                System.out.print("Enter day: ");
                Scanner scan9 = new Scanner(System.in);
                day = scan9.nextInt();
                if(day > 30){
                    System.out.println("Invalid date! Please try again");
                }
            else{
                if(day >= 23)
                    System.out.print("The Zodiac sign for September " + day + " 
is Libra.");
                else if(day < 23)
                    System.out.print("The Zodiac sign for Spetember " + day + " 
is Virgo.");
            }
            break;
                
                
            case 10:
                System.out.print("Enter day: ");
                Scanner scan10 = new Scanner(System.in);
                day = scan10.nextInt();
                if(day > 31){
                    System.out.println("Invalid date! Please try again");
                }
            else{
                if(day >= 23)
                    System.out.print("The Zodiac sign for October " + day + " is 
Scorpio.");
                else if(day < 23)
                    System.out.print("The Zodiac sign for October " + day + " is 
Libra.");
            }
            break;
                
                
            case 11:
                System.out.print("Enter day: ");
                Scanner scan11 = new Scanner(System.in);
                day = scan11.nextInt();
                if(day > 30){
                    System.out.println("Invalid date! Please try again");
                }
            else{
                if(day >= 22)
                    System.out.print("The Zodiac sign for November " + day + " i
s Sagittarius.");
                else if(day < 22)
                    System.out.print("The Zodiac sign for November " + day + " i
s Scorpio.");
            }
            break;
                
                
            case 12:
                System.out.print("Enter day: ");
                Scanner scan12 = new Scanner(System.in);
                day = scan12.nextInt();
                if(day > 31){
                    System.out.println("Invalid date! Please try again");
                }
            else{
                if(day >= 21)
                    System.out.print("The Zodiac sign for December " + day + " i
s Capricorn.");
                else if(day < 21)
                    System.out.print("The Zodiac sign for December " + day + " i
s Sagittarius.");
                }
            break;
                
                
            default:
            System.out.println("Invalid date! Please try again");
        }
     }
     
     catch(InputMismatchException e){
         System.out.println ("InputMismatchException: It must be an integer.");
      }
        
        
    } 
    
}
Output:
II). Question and answer

1. What exception types can be caught by the following handler?

catch (Exception e) {

Answer: For me, this handler will catch exceptions of type Exception. Therefore, it can catch any exception. But,
this could lead to a poor implementation because you are losing your valuable information about the type of
exception being thrown and causing your code to be less efficient. As a result, your program can be forced to
determine the type of exception before it can decide on having the best recovery strategy.

2. Is there anything wrong with the following exception handler as written? Will this code compile?

try {

} catch (Exception e) {

} catch (ArithmeticException a) {

Answer: For me, this first handler will catch exceptions of type Exception. Therefore, it can catch any exception
including ArithmeticException. But, the second handler can never be reached. Therefore, this code will not be able
to compile.

3. Is the following code legal?

try {

} finally {

Answer: It’s legal and very useful because a try statement does not need to have a catch block if it has a
finally block. But, if the code in the try statement has a multiple exit points and no associated catch
clauses, then the code in the finally block will executed even though the try block is exited. Therefore, it
makes sense to provide a finally block whenever there is a code that must need to always be executed.
This will include resource recovery code, such as the code to close I/O streams.

Potrebbero piacerti anche