9.
Define a package number and in that define Roman class and
implement romanToInteger() and import the method in another class.
Input: "LVIII" Output: 58
Explanation: L = 50, V= 5, III = 3.
// File: Roman.java inside the 'number' package
package number;
public class Roman
{
Public intromanToInteger(String s)
{
if (s == null || s.length() == 0)
{
return 0;
}
int result = 0;
for (inti = 0; i<s.length(); i++)
{
intcurrentVal = getValue(s.charAt(i));
if (i + 1 <s.length())
{
intnextVal = getValue(s.charAt(i + 1));
if (currentVal<nextVal)
{
result += nextVal - currentVal;
i++; // Skip the next character since it has already been considered
}
Else
{
result += currentVal;
}
} else {
result += currentVal;
}
}
return result;
}
Private intgetValue(char romanChar) {
switch (romanChar) {
case 'I':
return 1;
case 'V':
return 5;
case 'X':
return 10;
case 'L':
return 50;
case 'C':
return 100;
case 'D':
return 500;
case 'M':
return 1000;
default:
throw new IllegalArgumentException("Invalid Roman numeral character: " + romanChar);
}
}
}
// File: MainApp.java
importnumber.Roman;
public class MainApp {
public static void main(String[] args) {
Roman romanConverter = new Roman();
String inputRoman = "LVIII";
int result = romanConverter.romanToInteger(inputRoman);
System.out.println("Input: \"" + inputRoman + "\" Output: " + result);
}
}
Compilation :
>javac number/Roman.java
>javac MainApp.java
Run:
>java MainApp
Output:
Input: "LVIII" Output: 58
10. Write the below text in the file called pattern.txt and then find the frequency
count of the patterns ‘pe’, and ‘pi’
Peter Piper picked a peck of pickled peppers
A peck of pickled peppers Peter Piper picked
If Peter Piper picked a peck of pickled peppers
Where’s the peck of pickled peppers Peter Piper picked?
Expected Output:
‘pe’ – no of occurrences - 20
‘pi’ – no of occurrences – 12
importjava.io.BufferedReader;
importjava.io.FileReader;
importjava.io.IOException;
public class PatternFrequency {
public static void main(String[] args) {
// Specify the file path
String filePath = "C://Users//Shanti//Desktop//csmb java lab//pattern.txt";
try {
// Read the content of the file
String content = readFileContent(filePath);
// Count the occurrences of 'pe' and 'pi'
intcountPe = countPatternOccurrences(content, "pe");
intcountPi = countPatternOccurrences(content, "pi");
// Display the results
System.out.println("'pe' – no of occurrences - " + countPe);
System.out.println("'pi' – no of occurrences - " + countPi);
} catch (IOException e) {
System.err.println("Error reading the file: " + e.getMessage());
}
}
private static String readFileContent(String filePath) throws IOException {
StringBuilder content = new StringBuilder();
try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
String line;
while ((line = reader.readLine()) != null) {
content.append(line).append("\n");
}
}
returncontent.toString();
}
private static intcountPatternOccurrences(String text, String pattern) {
int count = 0;
int index = text.indexOf(pattern);
while (index != -1) {
count++;
index = text.indexOf(pattern, index + 1);
}
return count;
}
}
Pattern.txt
Peter Piper picked a peck of pickled peppers
A peck of pickled peppers Peter Piper picked
If Peter Piper picked a peck of pickled peppers
Where’s the peck of pickled peppers Peter Piper picked?
Output:
'pe' â?? no of occurrences - 16
'pi' â?? no of occurrences - 8
11. Input a mobile number and check the number is valid mobile number or not.
If the given Number Exceeds length of 10 raise Invalid Mobile Number-
ArrayIndexOutofBounds Exception
If the given Number less than the length of 10 raise Invalid Mobile
Number – LengthNotSufficientException
If the given Number contain any character other than digit raise Invalid
Mobile Number –NumberFormatException
Sample Input Expected Output – 1
9885089465 Valid number
98567890121 InvalidArrayIndexOutofBounds Exception
88664433 Invalid LengthNotSufficientException
98ab@123 InvalidNumberFormatException
public class MobileNumberValidator {
public static void main(String[] args) {
try {
validateMobileNumber("9885089465"); // Valid number
validateMobileNumber("98567890121"); // InvalidArrayIndexOutofBounds Exception
validateMobileNumber("88664433"); // Invalid LengthNotSufficientException
validateMobileNumber("98ab@123"); // InvalidNumberFormatException
} catch (InvalidArrayIndexException e) {
System.out.println("InvalidArrayIndexOutofBounds Exception: " + e.getMessage());
} catch (LengthNotSufficientException e) {
System.out.println("Invalid LengthNotSufficientException: " + e.getMessage());
} catch (NumberFormatException e) {
System.out.println("InvalidNumberFormatException: " + e.getMessage());
}
}
static void validateMobileNumber(String mobileNumber)
throwsInvalidArrayIndexException, LengthNotSufficientException,
NumberFormatException {
if (mobileNumber.length() > 10) {
throw new InvalidArrayIndexException("Exceeds length of 10");
} else if (mobileNumber.length() < 10) {
throw new LengthNotSufficientException("Less than length of 10");
}
// Check if the string contains only digits
if (!mobileNumber.matches("\\d+")) {
throw new NumberFormatException("Contains non-digit characters");
}
System.out.println("Valid number");
}
}
classInvalidArrayIndexException extends Exception {
publicInvalidArrayIndexException(String message) {
super(message);
}
}
classLengthNotSufficientException extends Exception {
publicLengthNotSufficientException(String message) {
super(message);
}
}
Output:
Valid number
InvalidArrayIndexOutofBounds Exception: Exceeds length of 10
NOTE :
whyInvalid LengthNotSufficientException and InvalidNumberFormatException are not
come into output ?
Answer : FIRSTLY we provide the valid number so no problem output came
Then exception raised then move to catch block to handle the exception so
handled
Successfully then exception is come into output
*** here once the catch block executed then never go back to try block . in case try
block
Have next statements those are not executed .
12.Implement a Reservation system which allows the persons to book seats.
Define reserve method initially with 100 seats. Now create one or more
person threads to book seats. At any time it should allow only one person
thread to access the reserve method.
Expected Output:
Person-1 entered.
Available seats: 10 Requested seats: 5
Seat Available. Reserve now :-)
5 seats reserved.
Person-1 leaving.
Person-3 leaving.
Class ReservationSystem {
private static intavailableSeats = 100;
public synchronized void reserve(String personName, intrequestedSeats) {
System.out.println(personName + " entered.");
System.out.println("Available seats: " + availableSeats + " Requested seats: " +
requestedSeats);
if (availableSeats>= requestedSeats) {
System.out.println("Seat Available. Reserve now :-)");
availableSeats -= requestedSeats;
System.out.println(requestedSeats + " seats reserved.");
} else {
System.out.println("Not enough seats available. Reservation failed.");
}
System.out.println(personName + " leaving.");
}
}
Class PersonThread extends Thread {
private ReservationSystem reservationSystem;
private String personName;
privateintrequestedSeats;
public PersonThread(ReservationSystem reservationSystem, String personName, int
requestedSeats) {
this.reservationSystem = reservationSystem;
this.personName = personName;
this.requestedSeats = requestedSeats;
}
public void run() {
reservationSystem.reserve(personName, requestedSeats);
}
}
public class ReservationSystemDemo {
public static void main(String[] args) {
ReservationSystem reservationSystem = new ReservationSystem();
// Create multiple PersonThread instances to simulate multiple persons trying to reserve
seats
PersonThread person1 = new PersonThread(reservationSystem, "Person-1", 5);
PersonThread person2 = new PersonThread(reservationSystem, "Person-2", 20);
PersonThread person3 = new PersonThread(reservationSystem, "Person-3", 10);
// Start the threads
person1.start();
person2.start();
person3.start();
}
}
Output:
Person-1 entered.
Available seats: 100 Requested seats: 5
Seat Available. Reserve now :-)
5 seats reserved.
Person-1 leaving.
Person-3 entered.
Available seats: 95 Requested seats: 10
Seat Available. Reserve now :-)
10 seats reserved.
Person-3 leaving.
Person-2 entered.
Available seats: 85 Requested seats: 20
Seat Available. Reserve now :-)
20 seats reserved.
Person-2 leaving.