gpt4 book ai didi

java - 在方法中使用 for 循环检查字符串中的数组项 - 打印 12 行而不是 1 行

转载 作者:行者123 更新时间:2023-12-01 23:30:18 25 4
gpt4 key购买 nike

Java新手,请多多指教!

创建一个简单的教育应用程序来检查论文句子中的人称代词。我几乎已经让它工作了,我的问题是该方法打印 12 次(而不是检查 12 个代词并打印一行)。

public static void pronoun (String thesis){    

String [] personalPronouns = {"I","me","you","we","us","our","he","him","she","her","they","them"};

for (int i = 0; i < 12; i++){
if (thesis.contains(personalPronouns[i])){
System.out.println("Oops! Looks like your thesis contains personal pronouns. Remember, avoid using I, you, me, we, us, our, etc. in persuasive essays.");
} else {
System.out.println("Looks good. Now it's time to start writing! Your essay outline is saved to a txt file called EssayTutorOutline.");
}
}
}

如果我输入“我有论文”。它返回这个:

看起来不错...

看起来不错...

看起来不错...

看起来不错...

看起来不错...

看起来不错...

哎呀!...

看起来不错...

看起来不错...

看起来不错...

看起来不错...

看起来不错...

我相信这对你们大多数人来说都是显而易见的。整晚都在谷歌上寻找答案。任何帮助表示赞赏。

最佳答案

浏览一下你的代码,一边解释一边进行,你就会发现问题所在。

// repeat for each number from 0 to 11
for (int i = 0; i < 12; i++) {
// if this string contains the string in personalPronouns[i]
if (thesis.contains(personalPronouns[i])){
// print this message
System.out.println("Oops! Looks like your thesis contains personal pronouns. Remember, avoid using I, you, me, we, us, our, etc. in persuasive essays.");
} else { // otherwise
// print this message
System.out.println("Looks good. Now it's time to start writing! Your essay outline is saved to a txt file called EssayTutorOutline.");
}
}

您想要做的只是弄清楚是否存在任何代词。您可以通过设置一个 boolean 变量(称为标志)来做到这一点,只要人称代词匹配,该变量就会发生变化:

boolean personalPronounSeen = false;
for (int i = 0; i < 12; i++) {
if (thesis.contains(personalPronouns[i])){
personalPronounSeen = true;
}
}
if(personalPronounSeen) {
// print your message...
}

请注意,虽然使用标志是解决一般问题的通用解决方案,但由于多种原因,这仍然无法达到您想要的效果。特别是,contains 方法匹配子字符串,因此您会得到很多误报,例如任何大写的 I、单词 welcomedelicious ,等等。您也不会匹配任何大小写不同的人称代词。

更稳健的方法是在空格上分割thesis,从每个结果单词中去掉标点符号,将它们全部添加到 Set 中。 ,然后查看 Set#contains 是否包含任何代词。如果您使用TreeSet,您可以告诉集合忽略大小写并将“We”“we”视为相同:

Set<String> wordList = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);
wordList.add("we");
wordList.contains("We"); // true

最后,看一下 enhanced for loop ;它使数组或集合的迭代更加清晰并且不易出错。如果您确实需要手动迭代,请始终使用 personalPronouns.length 而不是硬编码数字 12

关于java - 在方法中使用 for 循环检查字符串中的数组项 - 打印 12 行而不是 1 行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19439690/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com