[英]Making singular words plural trouble
我正在制作一個可以使單數復數的程序,但是我不確定如何檢查所創建的字符串數組中的異常。 我知道還有更多例外,但是現在我只想得到我正在工作的東西。 我創建了一個名為“ checkExceptions”的方法,但是在程序繼續運行之前,我將在其中放入什么內容以便程序首先檢查該方法呢?
import java.util.Scanner;
public class FormingPlurals {
static final String SENTINEL = "done";
static final Scanner IN = new Scanner(System.in);
static String[] exceptions = {"fish", "fox", "deer", "moose", "sheep", "cattle"};
public static void run() {
while (true) {
System.out.println("Enter a word to make it plural. Enter 'done' to stop: ");
String noun = IN.nextLine();
if (noun.toLowerCase().equals(SENTINEL)) {
System.out.println("Goodbye...");
break;
}
System.out.println(makePlural(noun) + " ");
}
}
public static void checkExceptions() {
}
static String makePlural(String singularWord) {
String pluralWord = "";
int length = singularWord.length();
String checker = singularWord.substring(0, singularWord.length() - 1);
char lastLetter = singularWord.charAt(singularWord.length() - 1);
if (length == 1) {
pluralWord = singularWord + "'s";
} else
switch (lastLetter) {
case 's':
case 'x':
case 'z':
pluralWord = singularWord + "es";
break;
case 'h':
if ((singularWord.charAt(singularWord.length() - 2) == 'c') || (singularWord.charAt(singularWord.length() - 2) == 's')) {
pluralWord = singularWord + "es";
break;
}
case 'f':
if (EnglishConsonant(singularWord.charAt(singularWord.length() - 2))) {
pluralWord = checker + "ves";
break;
}
case 'y':
if (EnglishConsonant(singularWord.charAt(singularWord.length() - 2))) {
pluralWord = checker + "ies";
break;
}
default:
pluralWord = singularWord + "s";
break;
}
return pluralWord;
}
public static boolean EnglishConsonant(char ch) {
switch (Character.toLowerCase(ch)) {
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
return false;
default:
return true;
}
}
public static void main(String[] args) {
run();
}
}
也可以使用數組來做到這一點,但是在這種情況下使用映射會更容易。 您可以創建地圖
Map<String,String> irregularPlurals = new HashMap<>();
irregularPlurals.put("sheep","sheep");
irregularPlurals.put("fox","foxes");
然后,您可以簡單地使用Map
接口的方法,例如get()
或containsKey()
來檢查給定單詞是否具有不規則的復數形式。 一個簡單的檢查方法是:
String irregularPlural = irregularPlurals.get(singularWord);
if (irregularPlural != null){
return irregularPlural ;
}
順便說一句,重命名方法checkException()
是一個好主意,因為在Java異常中,檢查的異常是語言概念,因此讀者可能會認為該方法與處理Java異常有關。
首先,我將異常數組放置在makePlural
自身內部並在那里進行處理。
其次,我將從最專業的情況轉到最小的情況,所以
另外,目前我找到一個匹配無論是在例外情況或特殊復數,我會計算並立即返回結果,以防止其他規則與匹配,並添加更多的東西pluralWord
如果我必須對異常使用函數,那就是
public static boolean isException(String word){
String[] exceptions={"fish", "deer"};
for(int i=0;i<exceptions.length();i++) {
if(exceptions[i].equals(word))
return true;
}
return false;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.