更改 “or” 为 “our”。

huangapple go评论73阅读模式
英文:

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[] {&#39;a&#39;,&#39;e&#39;,&#39;i&#39;,&#39;o&#39;,&#39;u&#39;};
boolean hasVowel = false;
boolean running = true;
boolean oR = false;
while(running){
//Check for word
System.out.println(&quot;Enter a word more than 4 letters long or type quit to stop&quot;);
String word = input.nextLine();
if(word.equalsIgnoreCase(&quot;quit&quot;)){
System.exit(0);
}
while(word.length() &lt;= 4){
System.out.println(&quot;That word is not more than 4 letters long&quot;);
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(&quot;r&quot;)){
if(x == &#39;o&#39;) {
oR = true;
System.out.println(&quot;Has or&quot;);
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, &quot;u&quot;);
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[] {&#39;a&#39;,&#39;e&#39;,&#39;i&#39;,&#39;o&#39;,&#39;u&#39;};
boolean hasVowel = false;
boolean running = true;
boolean oR = false;
while(running){
//Check for word
System.out.println(&quot;Enter a word more than 4 letters long or type quit to stop&quot;);
String word = input.nextLine();
if(word.equalsIgnoreCase(&quot;quit&quot;)){
System.exit(0);
}
while(word.length() &lt;= 4){
System.out.println(&quot;That word is not more than 4 letters long&quot;);
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(&quot;r&quot;)){
if(x == &#39;o&#39;) {
oR = true;
System.out.println(&quot;Has or&quot;);
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, &quot;u&quot;);
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:不替换为rubour
  • cor:不替换为decourmucour,只替换为rancoursuccour
  • dor:只有ardourcandourodoursplendor是有效的,不需要在dorcondorcorridorvendor等中进行替换
  • for:不替换为four
  • gor:只替换为clangourrigourvigour,不在mortgagorpledgorturgor中进行替换
  • hor:根本无法替换:anchorauthorcamphor
  • ior元音需要在behaviorpaviorsavior中替换
  • lor:在bachelorchancellorcounsellorjailorsailortailor等中不需要替换
  • mor:实际上应该是a[r]morumor,如armorclamorglamor,不在mortremor中替换
  • nor:只在honordemeanor及其派生词中需要替换,在donormanorminorsignortenor等中不需要替换
  • por:在saporvapor中需要,在stuportorpor中不需要
  • vor:应该是avorervor,如flavorfervor,不在salvorsurvivor中替换

其他以剩余辅音[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(&quot;(\\w+[^aeiou])or&quot;, &quot;$1our&quot;);
}

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: no rubour
  • cor: no decour, mucour, only rancour/succour
  • dor: only ardour, candour, odour, splendor are valid, no replacement needed in dor, condor, corridor, vendor, etc.
  • for: is not replaced with four
  • gor: only clangour, rigour, vigour, and no replacement in: mortgagor, pledgor, turgor
  • hor: not replaceable at all: anchor, author, camphor, etc.
  • ior: vowel need to replace in behavior, pavior, savior
  • lor: no replacement needed in bachelor, chancellor, counsellor, jailor, sailor, tailor etc.
  • mor: actually it should be a[r]mor or umor as in armor, clamor, glamor, humor, no replacement in mor, tremor
  • nor: replacement needed only in honor, demeanor and their derivatives, no replacement in donor, manor, minor, signor, tenor, etc.
  • por: needed in sapor, vapor, not in stupor, torpor
  • vor: should be avor/ervor as in flavor, fervor, not in salvor, 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(&quot;(((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&quot;,
        &quot;$1our&quot;
);
}

Test:

String[] replaceableWords = {
    &quot;arbor&quot;, &quot;harbor&quot;, &quot;neighbor&quot;, &quot;labor&quot;, &quot;tabor&quot;,
    &quot;rancor&quot;, &quot;succor&quot;,
    &quot;ardor&quot;, &quot;candor&quot;, &quot;odor&quot;, &quot;splendor&quot;,
    &quot;clangor&quot;, &quot;vigor&quot;, &quot;rigor&quot;,
    &quot;misbehavior&quot;, &quot;pavior&quot;, &quot;savior&quot;,
    &quot;color&quot;, &quot;dolor&quot;, &quot;parlor&quot;, &quot;valor&quot;,
    &quot;amor&quot;, &quot;armor&quot;, &quot;tumor&quot;, &quot;humor&quot;, &quot;clamor&quot;, &quot;glamor&quot;,
    &quot;dishonor&quot;, &quot;honor&quot;, &quot;misdemeanor&quot;,
    &quot;vapor&quot;, &quot;sapor&quot;,
    &quot;flavor&quot;, &quot;endeavor&quot;, &quot;favor&quot;, &quot;savor&quot;, &quot;disfavor&quot;
};

int successCount = 0;
for (String word : replaceableWords) {
    String replaced = changePrefixOrToOur(word);
    successCount += replaced.endsWith(&quot;our&quot;) ? 1 : 0;
    //System.out.printf(&quot;%s -&gt; %s ? %s%n&quot;, word, replaced, replaced.endsWith(&quot;our&quot;) ? &quot;OK&quot; : &quot;FAIL&quot;);
}

System.out.printf(&quot;Replaced  `or` to `our`: %d of %d words%n---%n%n&quot;, successCount, replaceableWords.length);

String[] notReplaceableWords = {
    &quot;rubor&quot;,
    &quot;decor&quot;, &quot;mucor&quot;,
    &quot;ambassador&quot;, &quot;condor&quot;, &quot;corridor&quot;, &quot;conquistador&quot;, &quot;dor&quot;, &quot;matador&quot;, &quot;picador&quot;, &quot;vendor&quot;,
    &quot;meteor&quot;,
    &quot;for&quot;,
    &quot;mortgagor&quot;, &quot;pledgor&quot;, &quot;turgor&quot;, &quot;tangor&quot;,
    &quot;abhor&quot;, &quot;anaphor&quot;, &quot;anchor&quot;, &quot;author&quot;, &quot;camphor&quot;, &quot;metaphor&quot;,
    &quot;anterior&quot;, &quot;prior&quot;, &quot;superior&quot;, &quot;warrior&quot;,
    &quot;Angkor&quot;,
    &quot;bachelor&quot;, &quot;counselor&quot;, &quot;chancellor&quot;, &quot;squalor&quot;, &quot;tailor&quot;, &quot;sailor&quot;, &quot;taylor&quot;,
    &quot;mor&quot;, &quot;tremor&quot;,
    &quot;nor&quot;, &quot;assignor&quot;, &quot;donor&quot;, &quot;governor&quot;, &quot;signor&quot;, &quot;minor&quot;, &quot;manor&quot;, &quot;tenor&quot;, &quot;intervenor&quot;,
    &quot;door&quot;, &quot;floor&quot;, &quot;moor&quot;, &quot;outdoor&quot;, &quot;poor&quot;, &quot;boor&quot;,
    &quot;por&quot;, &quot;sopor&quot;, &quot;torpor&quot;, &quot;stupor&quot;,
    &quot;advisor&quot;, &quot;censor&quot;, &quot;professor&quot;, &quot;processor&quot;, &quot;sensor&quot;, &quot;tensor&quot;,
    &quot;actor&quot;, &quot;doctor&quot;, &quot;director&quot;, &quot;factor&quot;, &quot;bettor&quot;,
    &quot;liquor&quot;, &quot;languor&quot;, &quot;fluor&quot;,
    &quot;survivor&quot;, &quot;salvor&quot;,
    &quot;xor&quot;, &quot;luxor&quot;, &quot;taxor&quot;,
    &quot;mayor&quot;,
    &quot;razor&quot;, &quot;seizor&quot;, &quot;vizor&quot;
};

for (String word : notReplaceableWords) {
    String replaced = changePrefixOrToOur(word);
    successCount += replaced.endsWith(&quot;or&quot;) ? 1 : 0;
    //System.out.printf(&quot;%s -&gt; %s ? %s%n&quot;, word, replaced, replaced.endsWith(&quot;or&quot;) ? &quot;OK&quot; : &quot;FAIL&quot;);
}
System.out.printf(&quot;Not replaced  `or` to `our`: %d of %d words%n&quot;, successCount - replaceableWords.length, notReplaceableWords.length);

Output:

Replaced `or` to `our`: 37 of 37 words
---
Not replaced  `or` to `our`: 79 of 79 words

huangapple
  • 本文由 发表于 2020年10月18日 04:33:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/64407061.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定