英文:
Changing or to our
问题
import java.util.Scanner;
public class main {
    public static void main(String[] args) {
        // Initializing Variables
        Scanner input = new Scanner(System.in);
        char[] vowels = new char[] {'a', 'e', 'i', 'o', 'u'};
        boolean hasVowel = false;
        boolean running = true;
        boolean oR = false;
        while(running) {
            // Check for word
            System.out.println("Enter a word more than 4 letters long or type quit to stop");
            String word = input.nextLine();
            if(word.equalsIgnoreCase("quit")){
                System.exit(0);
            }
            while(word.length() <= 4){
                System.out.println("That word is not more than 4 letters long");
                word = input.next();
            }
            // Used to insert words
            StringBuilder stringBuilder = new StringBuilder(word);
            // Check for the letters
            char x = word.charAt(word.length() - 2);
            if(word.endsWith("r")){
                if(x == 'o') {
                    oR = true;
                    System.out.println("Has or");
                    for (char c : vowels) {
                        if (c == word.charAt(word.length() - 3)) {
                            hasVowel = true;
                            oR = false;
                        }
                    }
                }
            }
            // Output
            if(hasVowel){
                System.out.println(word);
            }
            else {
                if(oR == true) {
                    stringBuilder.insert(word.length() - 1, "u");
                    System.out.println(stringBuilder.toString());
                }
                else if (oR == false) {
                    System.out.println(word);
                }
            }
            System.out.println(hasVowel);
            System.out.println(word.charAt(word.length() - 3));
        }
    }
}
英文:
I've been working on a program for school for some time now that is supposed to change every word that ends in "or" and does not have a vowel before the "or". However I am running into an issue where it replaces the letters for words such as paper and letter into papeur and letteur. Here's my code:
import java.util.Scanner;
public class main {
public static void main(String[] args){
//Initializing Variables
Scanner input = new Scanner(System.in);
char[] vowels = new char[] {'a','e','i','o','u'};
boolean hasVowel = false;
boolean running = true;
boolean oR = false;
while(running){
//Check for word
System.out.println("Enter a word more than 4 letters long or type quit to stop");
String word = input.nextLine();
if(word.equalsIgnoreCase("quit")){
System.exit(0);
}
while(word.length() <= 4){
System.out.println("That word is not more than 4 letters long");
word = input.next();
}
//Used to insert words
StringBuilder stringBuilder = new StringBuilder(word);
//Check for the letters
char x = word.charAt(word.length()-2);
if(word.endsWith("r")){
if(x == 'o') {
oR = true;
System.out.println("Has or");
for (char c : vowels) {
if (c == word.charAt(word.length() - 3)) {
hasVowel = true;
oR = false;
}
}
}
}
//output
if (hasVowel){
System.out.println(word);
}
else{
if(oR = true) {
stringBuilder.insert(word.length() - 1, "u");
System.out.println(stringBuilder.toString());
}
else if (oR = false) {
System.out.println(word);
}
}
System.out.println(hasVowel);
System.out.println(word.charAt(word.length()-3));
}
}
}
If someone could help me out that would be amazing!
答案1
得分: 2
你的问题在于这一行:
if(oR = true) {
这会始终为true,因为这是一个赋值操作,而不是一个相等性检查。你应该在这里使用==。
另外要注意,与此相对应的else 子句:
else if (oR = false) {
可以简化为:
else {
因为如果一个布尔值不是true,它必定是false。
英文:
Your problem is this line:
if(oR = true) {
This will always be true, because it is an assignment rather than an equality check.  You want == here.
Also note that the else clause that goes with this:
else if (oR = false) {
can be just:
else {
since if a boolean value isn't true, it has to be false.
答案2
得分: 0
这样你就可以编辑
public static void main(String[] args) {
    // 初始化变量
    Scanner input = new Scanner(System.in);
    char[] vowels = new char[] {'a', 'e', 'i', 'o', 'u'};
    boolean hasVowel = false;
    boolean running = true;
    boolean oR = false;
    while(running){
        // 检查单词
        System.out.println("输入一个至少有4个字母的单词,或者输入 quit 停止");
        String word = input.nextLine();
        if(word.equalsIgnoreCase("quit")){
            System.exit(0);
        }
        while(word.length() <= 4){
            System.out.println("该单词不超过4个字母");
            word = input.next();
        }
        // 用于插入单词
        StringBuilder stringBuilder = new StringBuilder(word);
        // 检查字母
        char x = word.charAt(word.length() - 2);
        if(word.endsWith("r")){
            if(x == 'o') {
                oR = true;
                System.out.println("含有 'or'");
                for (char c : vowels) {
                    if (c == word.charAt(word.length() - 3)) {
                        hasVowel = true;
                        oR = false;
                    }
                }
            }
        }
        // 输出
        if (hasVowel){
            System.out.println(word);
        }
        else{
            if(oR) {
                stringBuilder.insert(word.length() - 1, "u");
                System.out.println(stringBuilder.toString());
            }
            else {
                System.out.println(word);
            }
        }
        System.out.println(hasVowel);
        System.out.println(word.charAt(word.length() - 3));
    }
}
英文:
This way you can edit
public static void main(String[] args){
//Initializing Variables
Scanner input = new Scanner(System.in);
char[] vowels = new char[] {'a','e','i','o','u'};
boolean hasVowel = false;
boolean running = true;
boolean oR = false;
while(running){
//Check for word
System.out.println("Enter a word more than 4 letters long or type quit to stop");
String word = input.nextLine();
if(word.equalsIgnoreCase("quit")){
System.exit(0);
}
while(word.length() <= 4){
System.out.println("That word is not more than 4 letters long");
word = input.next();
}
//Used to insert words
StringBuilder stringBuilder = new StringBuilder(word);
//Check for the letters
char x = word.charAt(word.length()-2);
if(word.endsWith("r")){
if(x == 'o') {
oR = true;
System.out.println("Has or");
for (char c : vowels) {
if (c == word.charAt(word.length() - 3)) {
hasVowel = true;
oR = false;
}
}
}
}
//output
if (hasVowel){
System.out.println(word);
}
else{
if(oR) { //if(oR == true)
stringBuilder.insert(word.length() - 1, "u");
System.out.println(stringBuilder.toString());
}
else { //else if (!oR) //else if (oR == false) 
System.out.println(word);
}
}
System.out.println(hasVowel);
System.out.println(word.charAt(word.length()-3));
}
}
答案3
得分: 0
如评论中所提到的,这个任务可以使用正则表达式来解决,因为它是在字符串中搜索和替换子字符串的一种自然方式。
将后缀-or替换为后缀-our的基本正则表达式,条件是-or前面不是元音,如下所示:
public String simpleOrToOur(String word) {
    return word.replaceAll("(\\w+[^aeiou])or", "$1our");
}
然而,最初的规则似乎不正确,因为在多种情况下,在辅音之前出现or时不应进行替换,并且可能在-ior前缀中发生替换:
bor:不替换为rubourcor:不替换为decour、mucour,只替换为rancour、succourdor:只有ardour、candour、odour、splendor是有效的,不需要在dor、condor、corridor、vendor等中进行替换for:不替换为fourgor:只替换为clangour、rigour、vigour,不在mortgagor、pledgor、turgor中进行替换hor:根本无法替换:anchor、author、camphor等ior:元音需要在behavior、pavior、savior中替换lor:在bachelor、chancellor、counsellor、jailor、sailor、tailor等中不需要替换mor:实际上应该是a[r]mor或umor,如armor、clamor、glamor,不在mor、tremor中替换nor:只在honor、demeanor及其派生词中需要替换,在donor、manor、minor、signor、tenor等中不需要替换por:在sapor、vapor中需要,在stupor、torpor中不需要vor:应该是avor、ervor,如flavor、fervor,不在salvor、survivor中替换
其他以剩余辅音[jkqstwxyz]or开头的前缀也不需要替换为-our。
话虽如此,可以实现一个更好的匹配正则表达式,其中包括了前缀和提到的子部分,并使用OR |连接,然后再加上后缀-or:
public static String changePrefixOrToOur(String word) {
    return word.replaceAll("(((h?ar|[lt]a|neigh)b)|(ranc|succ)|((ar|can|o|splen)d)|((clan|[rv]i)g)|(vi)|(([cd]o|par|va)l)|((ar?|u)m)|((ho|demea)n)|([sv]ap)|((a|er)v))or",
        "$1our");
}
测试:
String[] replaceableWords = {
    "arbor", "harbor", "neighbor", "labor", "tabor",
    "rancor", "succor",
    "ardor", "candor", "odor", "splendor",
    "clangor", "vigor", "rigor",
    "misbehavior", "pavior", "savior",
    "color", "dolor", "parlor", "valor",
    "amor", "armor", "tumor", "humor", "clamor", "glamor",
    "dishonor", "honor", "misdemeanor",
    "vapor", "sapor",
    "flavor", "endeavor", "favor", "savor", "disfavor"
};
int successCount = 0;
for (String word : replaceableWords) {
    String replaced = changePrefixOrToOur(word);
    successCount += replaced.endsWith("our") ? 1 : 0;
}
System.out.printf("Replaced  `or` to `our`: %d of %d words%n---%n%n", successCount, replaceableWords.length);
String[] notReplaceableWords = {
    "rubor",
    "decor", "mucor",
    "ambassador", "condor", "corridor", "conquistador", "dor", "matador", "picador", "vendor",
    "meteor",
    "for",
    "mortgagor", "pledgor", "turgor", "tangor",
    "abhor", "anaphor", "anchor", "author", "camphor", "metaphor",
    "anterior", "prior", "superior", "warrior",
    "Angkor",
    "bachelor", "counselor", "chancellor", "squalor", "tailor", "sailor", "taylor",
    "mor", "tremor",
    "nor", "assignor", "donor", "governor", "signor", "minor", "manor", "tenor", "intervenor",
    "door", "floor", "moor", "outdoor", "poor", "boor",
    "por", "sopor", "torpor", "stupor",
    "advisor", "censor", "professor", "processor", "sensor", "tensor",
    "actor", "doctor", "director", "factor", "bettor",
    "liquor", "languor", "fluor",
    "survivor", "salvor",
    "xor", "luxor", "taxor",
    "mayor",
    "razor", "seizor", "vizor"
};
for (String word : notReplaceableWords) {
    String replaced = changePrefixOrToOur(word);
    successCount += replaced.endsWith("or") ? 1 : 0;
}
System.out.printf("Not replaced  `or` to `our`: %d of %d words%n", successCount - replaceableWords.length, notReplaceableWords.length);
输出:
Replaced
<details>
<summary>英文:</summary>
As mentioned in the comments, this task could be resolved using regular expressions because it is a natural way of searching and replacing substrings in strings.
The basic regular expression to replace suffix `-or` with suffix `-our` on the condition that `-or` is not preceded by a vowel is as follows:
```java
public String simpleOrToOur(String word) {
return word.replaceAll("(\\w+[^aeiou])or", "$1our");
}
However, the initial rule does not seem to be correct because the replacements should NOT occur in multiple cases when there is a consonant before or, and may occur for -ior prefix:
bor: norubourcor: nodecour, mucour, onlyrancour/succourdor: onlyardour, candour, odour, splendorare valid, no replacement needed indor, condor, corridor, vendor, etc.for: is not replaced withfourgor: onlyclangour, rigour, vigour, and no replacement in:mortgagor, pledgor, turgorhor: not replaceable at all:anchor, author, camphor,etc.ior: vowel need to replace inbehavior, pavior, saviorlor: no replacement needed inbachelor, chancellor, counsellor, jailor, sailor, tailoretc.mor: actually it should bea[r]mororumoras inarmor, clamor, glamor, humor, no replacement inmor, tremornor: replacement needed only inhonor, demeanorand their derivatives, no replacement indonor, manor, minor, signor, tenor, etc.por: needed insapor, vapor, not instupor, torporvor: should beavor/ervoras inflavor, fervor, not insalvor, survivor
Other prefixes with remaining consonants [jkqstwxyz]or do not need replacement to -our either.
That being said, a better matching regexp consisting of prefix including the mentioned subparts joined with OR | and suffix -or may be implemented:
public static String changePrefixOrToOur(String word) {
    return word.replaceAll("(((h?ar|[lt]a|neigh)b)|(ranc|succ)|((ar|can|o|splen)d)|((clan|[rv]i)g)|(vi)|(([cd]o|par|va)l)|((ar?|u)m)|((ho|demea)n)|([sv]ap)|((a|er)v))or",
        "$1our"
);
}
Test:
String[] replaceableWords = {
    "arbor", "harbor", "neighbor", "labor", "tabor",
    "rancor", "succor",
    "ardor", "candor", "odor", "splendor",
    "clangor", "vigor", "rigor",
    "misbehavior", "pavior", "savior",
    "color", "dolor", "parlor", "valor",
    "amor", "armor", "tumor", "humor", "clamor", "glamor",
    "dishonor", "honor", "misdemeanor",
    "vapor", "sapor",
    "flavor", "endeavor", "favor", "savor", "disfavor"
};
int successCount = 0;
for (String word : replaceableWords) {
    String replaced = changePrefixOrToOur(word);
    successCount += replaced.endsWith("our") ? 1 : 0;
    //System.out.printf("%s -> %s ? %s%n", word, replaced, replaced.endsWith("our") ? "OK" : "FAIL");
}
System.out.printf("Replaced  `or` to `our`: %d of %d words%n---%n%n", successCount, replaceableWords.length);
String[] notReplaceableWords = {
    "rubor",
    "decor", "mucor",
    "ambassador", "condor", "corridor", "conquistador", "dor", "matador", "picador", "vendor",
    "meteor",
    "for",
    "mortgagor", "pledgor", "turgor", "tangor",
    "abhor", "anaphor", "anchor", "author", "camphor", "metaphor",
    "anterior", "prior", "superior", "warrior",
    "Angkor",
    "bachelor", "counselor", "chancellor", "squalor", "tailor", "sailor", "taylor",
    "mor", "tremor",
    "nor", "assignor", "donor", "governor", "signor", "minor", "manor", "tenor", "intervenor",
    "door", "floor", "moor", "outdoor", "poor", "boor",
    "por", "sopor", "torpor", "stupor",
    "advisor", "censor", "professor", "processor", "sensor", "tensor",
    "actor", "doctor", "director", "factor", "bettor",
    "liquor", "languor", "fluor",
    "survivor", "salvor",
    "xor", "luxor", "taxor",
    "mayor",
    "razor", "seizor", "vizor"
};
for (String word : notReplaceableWords) {
    String replaced = changePrefixOrToOur(word);
    successCount += replaced.endsWith("or") ? 1 : 0;
    //System.out.printf("%s -> %s ? %s%n", word, replaced, replaced.endsWith("or") ? "OK" : "FAIL");
}
System.out.printf("Not replaced  `or` to `our`: %d of %d words%n", successCount - replaceableWords.length, notReplaceableWords.length);
Output:
Replaced `or` to `our`: 37 of 37 words
---
Not replaced  `or` to `our`: 79 of 79 words
				通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论