Week 8
Week 8
In Java, the exception hierarchy begins with the Throwable class, which
has two main subclasses: Error and Exception. Error represents serious
system-level issues, while Exception is further divided into checked and
unchecked exceptions. Checked exceptions must be handled explicitly,
while unchecked exceptions indicate runtime errors and don't require
explicit handling.
1. In this challenge, you must read an integer, a double, and a String from stdin, then print
the values according to the instructions in the Output Format section below. To make the
problem a little easier, a portion of the code is provided for you in the editor. Note: We
recommend completing Java stdin and stdout I before attempting this challenge.
import java.util.Scanner;
Input (stdin)
42
3.1415
Welcome to HackerRank's Java tutorials!
Expected Output
String: Welcome to HackerRank's Java tutorials!
Double: 3.1415
Int: 42
2. Implement a Java program with a method to calculate and print the average of an array
of integers. The average should be calculated as the sum of all elements divided by the
total number of elements. Exception Handling:Handle the case where the array is empty
to avoid an arithmetic exception. If the array is empty, throw an ArithmeticException
with the message "Cannot calculate average of an empty array." Output Format:Print the
calculated average if the array is non-empty. If an empty array is encountered, catch the
ArithmeticException and print an error message.
int[] numbers = {10, 20, 30, 40, 50}; // Sample array of integers
try {
} catch (ArithmeticException e) {
if (arr.length == 0) {
int sum = 0;
sum += num;
Input
Average: 30.
Input
Output
3.You are given an integer n, you have to convert it into a string. Please complete the partially
completed code in the editor. If your code successfully converts n into a string s the code will
print "Good job". Otherwise, it will print "Wrong answer". n can range between -100 to 100
inclusive. Sample Input 0 100 Sample Output 0 Good job
import java.util.*;
import java.security.*;
public class Solution {
public static void main(String[] args) {
DoNotTerminate.forbidExit();
try {
Scanner in = new Scanner(System.in);
int n = in .nextInt();
in.close();
//String s=???; Complete this line below
String s=Integer.toString(n);
//Write your code here
if (n == Integer.parseInt(s)) {
System.out.println("Good job");
} else {
System.out.println("Wrong answer.");
}
} catch (DoNotTerminate.ExitTrappedException e) {
System.out.println("Unsuccessful Termination!!");
}
}
}
//The following class will prevent you from terminating the code
using exit(0)!
class DoNotTerminate {
Input
42
Output
Good job
Post lab
1.The Calendar class is an abstract class that provides methods for converting between a specific
instant in time and a set of calendar fields such as YEAR, MONTH, DAY_OF_MONTH, HOUR, and so
on, and for manipulating the calendar fields, such as getting the date of the next week.You are given
a date. You just need to write the method, getDay, which returns the day on that date. To simplify
your task, we have provided a portion of the code in the editor.
import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
import java.util.regex.*;
import java.util.stream.*;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;
class Result {
/*
* Complete the 'findDay' function below.
*
* The function is expected to return a STRING.
* The function accepts following parameters:
* 1. INTEGER month
* 2. INTEGER day
* 3. INTEGER year
*/
bufferedWriter.write(res);
bufferedWriter.newLine();
bufferedReader.close();
bufferedWriter.close();
}
}
Input
08 05 2015
Output
WEDNESDAY
Skill Session
1.Write a Java program that takes user input for two numbers, adds them, and handles the possibility
of an InputMismatchException. Perform the following steps:Use a Scanner to prompt the user to
enter the first number. Handle the potential InputMismatchException by catching the exception and
printing an error message. If the input for the first number is successful, proceed to prompt the user
to enter the second number. Again, handle the potential InputMismatchException for the second
number and print an appropriate error message. If both inputs are valid, calculate and print the sum
of the two numbers.
import java.util.InputMismatchException;
import java.util.Scanner;
try {
} catch (InputMismatchException e) {
} finally {
scanner.close();
Input
Enter the first number: 10
Output
Sum: 30
Input
Input
10
Output
3
3.You are required to compute the power of a number by implementing a calculator. Create a class
MyCalculator which consists of a single method long power (int, int). This method takes two integers,
n and p, as parameters and finds np. If either n or p is negative, then the method must throw an
exception which says, "n or p should not be negative". Also, if both and are zero, then the method
must throw an exception which says "n and p should not be zero."For example, -4 and -5 would
result in java.lang.Exception: n or p should not be negative.Complete the function power in class
MyCalculator and return the appropriate result after the power operation or an appropriate
exception as detailed above.
import java.util.Scanner;
class MyCalculator {
else {
return ((int)Math.pow(n,p));
}
}
}
try {
System.out.println(my_calculator.power(n, p));
} catch (Exception e) {
System.out.println(e);
}
}
}
}
Input
35
24
00
-1 -2
-1 3
Output
243
16
java.lang.Exception: n or p should
4.Create a User-defined Exception which must throw when the student B.Tech marks below 60% and
Company written test marks below 70% marks during the company recruitment process.
super(message);
class CompanyRecruitmentProcess {
throw new RecruitmentException("B.Tech marks below 60% or written test marks below
70%");
} else {
// Example usage
try {
recruitmentProcess.conductRecruitment(bTechMarks, writtenTestMarks);
} catch (RecruitmentException e) {
Input
B.Tech Marks: 55
Output
RecruitmentException: B.Tech marks below 60% or written test marks below 70%
5.Create a user defined Exception which must be throw when the given phone number of the
student contains alphabets or symbols and the number of digits not equal to 10.
super(message);
class Student {
if (!phoneNumber.matches("\\d{10}")) {
this.phoneNumber = phoneNumber;
return phoneNumber;
try {
student.setPhoneNumber("123456789A");
} catch (InvalidPhoneNumberException e) {
System.out.println("InvalidPhoneNumberException: " + e.getMessage());
Input
123456789A
Output
InvalidPhoneNumberException: Invalid phone number. Phone number must contain 10 digits only.
6.Create Student class with ID, name, gender, and branch. Use getter and setters. The ID must be 9-
digit number, name must not have special characters and digits, gender must be either M/F and
branch must be either ECE/CSE/ME/ECSE/CE/BT/EEE. Use toString () to format the details of Student.
Create user defined exceptions for checking validity of the data. If data is not valid throw an
appropriate user defined exception from setter methods.
super(message);
class Student {
// Constructor
public Student() {
return id;
if (String.valueOf(id).length() != 9) {
this.id = id;
}
return name;
if (!name.matches("[a-zA-Z ]+")) {
throw new InvalidDataException("Invalid name. Name must not contain special characters or
digits.");
this.name = name;
return gender;
this.gender = gender;
return branch;
}
public void setBranch(String branch) throws InvalidDataException {
if (!branch.matches("ECE|CSE|ME|ECSE|CE|BT|EEE")) {
throw new InvalidDataException("Invalid branch. Branch must be one of ECE, CSE, ME, ECSE,
CE, BT, or EEE.");
this.branch = branch;
@Override
return "Student ID: " + id + "\nName: " + name + "\nGender: " + gender + "\nBranch: " + branch;
// Example usage
try {
} catch (InvalidDataException e) {
}
}
Input
ID: 123456789
Gender: M
Branch: CSE
Output
Gender: M
Branch: CSE