Okay, this is a multi-step process. You already have a great utility method for converting Nepali digits to English digits. We'll leverage that for the first part of the problem.
Here's how we can approach the new requirement:
- Convert Nepali digits to English digits: Use your existing
nepaliToShort method.
- Extract the number: From the string (now with English digits), parse out the numerical part.
- Calculate years: Divide the months by 12 and apply the specified rounding logic (which seems to be "round up if there's any fraction, but 0 months is 0 years").
Math.ceil is perfect for this.
- Format the output: Return the number of years with "year" or "years".
Let's put it into code:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class NepaliNumberConverter {
/**
* Converts Nepali digits (०-९) in a string to English digits (0-9).
* Non-digit characters are preserved.
*
* @param nepaliNum The input string potentially containing Nepali numbers.
* @return A string with Nepali digits converted to English digits.
*/
public static String nepaliToShort(String nepaliNum) {
StringBuilder englishNum = new StringBuilder();
for (char ch : nepaliNum.toCharArray()) {
if (ch >= '०' && ch <= '९') {
englishNum.append((char) ('0' + (ch - '०')));
} else {
englishNum.append(ch); // Keep non-digit characters as-is (if any)
}
}
return englishNum.toString();
}
/**
* Converts a string containing Nepali months (e.g., "९ महिना", "१७ म")
* into a rounded number of English years.
*
* Rules:
* - The first numerical sequence in the string is taken as months.
* - "9 months" becomes "1 year".
* - "17 months" becomes "2 years".
* - This implies rounding up any fraction (Math.ceil), except for 0 months which is 0 years.
*
* @param nepaliMonthString The input string containing Nepali month information.
* @return A string representing the converted years (e.g., "1 year", "2 years"),
* or an error message if the number cannot be parsed.
*/
public static String convertNepaliMonthsToYears(String nepaliMonthString) {
if (nepaliMonthString == null || nepaliMonthString.trim().isEmpty()) {
return "0 years"; // Or throw IllegalArgumentException
}
// Step 1: Convert Nepali digits to English digits
String englishMixedString = nepaliToShort(nepaliMonthString);
// Step 2: Extract the numerical part using regex
Pattern pattern = Pattern.compile("\\d+"); // Matches one or more digits
Matcher matcher = pattern.matcher(englishMixedString);
int months = 0;
if (matcher.find()) {
try {
months = Integer.parseInt(matcher.group());
} catch (NumberFormatException e) {
// This shouldn't happen if nepaliToShort works, but good to be safe.
return "Error: Could not parse number from input.";
}
} else {
// No number found in the string (e.g., "invalid input")
return "Error: No month number found in input.";
}
// Step 3: Calculate years with rounding logic
long years;
if (months == 0) {
years = 0;
} else {
// Math.ceil rounds up to the nearest whole number.
// Example: 9/12.0 = 0.75 -> ceil(0.75) = 1
// Example: 17/12.0 = 1.41... -> ceil(1.41...) = 2
// Example: 12/12.0 = 1.0 -> ceil(1.0) = 1
years = (long) Math.ceil(months / 12.0);
}
// Step 4: Format the output string
if (years == 1) {
return "1 year";
} else {
return years + " years";
}
}
public static void main(String[] args) {
// Test cases:
System.out.println("Input: \"९ महिना\" -> Output: " + convertNepaliMonthsToYears("९ महिना")); // Expected: 1 year
System.out.println("Input: \"१७ म\" -> Output: " + convertNepaliMonthsToYears("१७ म")); // Expected: 2 years
System.out.println("Input: \"१२ महिना\" -> Output: " + convertNepaliMonthsToYears("१२ महिना")); // Expected: 1 year
System.out.println("Input: \"१३ महिना\" -> Output: " + convertNepaliMonthsToYears("१३ महिना")); // Expected: 2 years
System.out.println("Input: \"० महिना\" -> Output: " + convertNepaliMonthsToYears("० महिना")); // Expected: 0 years
System.out.println("Input: \"५ महिना\" -> Output: " + convertNepaliMonthsToYears("५ महिना")); // Expected: 1 year
System.out.println("Input: \"२४ महिना\" -> Output: " + convertNepaliMonthsToYears("२४ महिना")); // Expected: 2 years
System.out.println("Input: \"३६ महिना\" -> Output: " + convertNepaliMonthsToYears("३६ महिना")); // Expected: 3 years
System.out.println("Input: \" केवल ३७ \" -> Output: " + convertNepaliMonthsToYears(" केवल ३७ ")); // Expected: 4 years
System.out.println("Input: \"no number\" -> Output: " + convertNepaliMonthsToYears("no number")); // Expected: Error
System.out.println("Input: \"\" -> Output: " + convertNepaliMonthsToYears("")); // Expected: 0 years
System.out.println("Input: null -> Output: " + convertNepaliMonthsToYears(null)); // Expected: 0 years
}
}
Explanation:
nepaliToShort(String nepaliNum): This is your original method, included for completeness and used by the new method.
convertNepaliMonthsToYears(String nepaliMonthString):
- Input Validation: Checks for
null or empty strings to prevent errors and provide a default "0 years".
englishMixedString = nepaliToShort(nepaliMonthString);: Converts any Nepali digits in the input string to their English equivalents (e.g., "९ महिना" becomes "9 महिना").
Pattern.compile("\\d+"): This creates a regular expression pattern that matches one or more (+) digit characters (\d).
Matcher matcher = pattern.matcher(englishMixedString);: Creates a matcher object to find the pattern in the englishMixedString.
if (matcher.find()): Attempts to find the first occurrence of the digit pattern.
months = Integer.parseInt(matcher.group());: If a number is found, matcher.group() returns the matched string (e.g., "9", "17"), which is then parsed into an int.
try-catch: A NumberFormatException is caught in case parseInt fails, though less likely after \d+ ensures only digits are matched.
else block: If matcher.find() returns false (meaning no number was found in the string), it returns an error message.
long years; if (months == 0) { years = 0; } else { years = (long) Math.ceil(months / 12.0); }: This is the core conversion logic:
- It handles
0 months separately, as Math.ceil(0) is 0.
- For any
months > 0, months / 12.0 performs floating-point division (e.g., 9 / 12.0 = 0.75).
Math.ceil() then rounds this result up to the nearest whole number (e.g., ceil(0.75) = 1, ceil(1.41) = 2, ceil(1.0) = 1). This perfectly matches your "9 months -> 1 year" and "17 months -> 2 years" requirements.
- The result is cast to
long (or int if you prefer, is safer for very large numbers).