Есть много способов сделать это. Вот небольшая концепция. Это метод, в котором вы вводите строку месяца либо в виде полного имени, либо в виде правильной трехбуквенной аббревиатуры (регистр букв игнорируется) ИЛИ номер месяца (от 1 до 12). следующий месяц с указанного месяца возвращается.
Если Декабрь , то Январь возвращается.
Если апр , то возвращается Май .
Если 6 подается (июнь), затем Июль возвращается.
Вот метод:
/**
* Returns the next month that will follow the supplied month string. Either a
* full month name, a three letter month name abbreviation, or a month numerical
* value (from 1 to 12) can be supplied to this method.<br><br>
*
* @param month (Integer OR String) If String then a full month name or three
* letter abbreviation can be supplied. Letter case is ignored. If Integer is
* supplied then any value from 1 to 12 (inclusive) can be supplied.<br>
*
* @return (String) The full month name that will be next after the supplied
* month.
*/
public static String getNextMonth(Object month) {
String res = null;
String[] months = {"January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"};
// Is Integer supplied...
if (month instanceof Integer && (int)month >= 1 && (int)month <= 12) {
// Ternary used here to get desired month from Array
res = months[(((int)month - 1) == (months.length - 1) ? 0 : (int)month)];
return res;
}
// Is String supplied...
else if ((month instanceof String && month.toString().trim().equals("") || month.toString().length() < 3 ||
!Arrays.asList(months).toString().toLowerCase().contains(month.toString().toLowerCase()))) {
System.err.println("Invalid Month Supplied!" + System.lineSeparator());
// Do what you like with this error!
}
else {
for (int i = 0; i < months.length; i++) {
if (months[i].toLowerCase().startsWith(month.toString().toLowerCase())) {
// Ternary used here to get desired month from Array
res = months[(i == (months.length - 1) ? 0 : (i + 1))];
break;
}
}
}
return res;
}
Чтобы проверить этот метод, вы можете использовать что-то вроде этого:
Scanner input = new Scanner(System.in);
String ls = System.lineSeparator();
while (true) {
System.out.println("Enter Month: ");
String mon = input.nextLine();
if (mon.equalsIgnoreCase("q")) { break; } // Quit
String nextMon;
// Is the supplied text a integer numerical value?
if (mon.matches("\\d+")) {
// Convert it from string to integer.
int monthNum = Integer.parseInt(mon);
// Passing an integer Month value to the
// getNextMonth() method.
nextMon = getNextMonth(monthNum);
}
else {
// Passing a String month name or (3 letter
// abreviation) to the getNextMonth() method.
nextMon = getNextMonth(mon);
}
if (nextMon != null){
System.out.println(nextMon + ls);
}
}