基本上,我编写了扫描文档的代码,然后检查它是否就是我所说的“正确”字词。适当的单词是仅包含字母的单词,但后面可以加上标点符号。因此,“ hello”和“ for4893859。;。;;。”会是适当的词,但“ hi,jack”和“ anti-thing”将不是适当的词。该代码仅应打印正确的单词,但是由于某些原因,我认为它跳过了for循环,而仅打印所有单词。
Scanner test= new Scanner(new File("Test.txt"));
while(test.hasNext()) {
String word=test.next();
char [] curr=word.toCharArray();
boolean check1=false;
boolean check2=false;
for(int i=0; i<curr.length; i++) {
if(!Character.isLetter(curr[i])) {
check1=true;
System.out.println(check1);
continue;
}
if(check1 && Character.isLetter(curr[i])) {
check2=true;
System.out.println(check2);
break;
}
}
if((check1 && !check2)||(!check1 && !check2)) {
System.out.println(word);
}
答案 0 :(得分:0)
我不确定您的逻辑应该做什么。由于您的问题是关于是否打印单词的布尔逻辑,因此我认为将布尔逻辑重构得更清楚会有所帮助。在第二个和第三个 if 表达式上,您可以在两个地方执行此操作。这是您代码的等效版本:
Scanner test= new Scanner(new File("Test.txt"));
while(test.hasNext()) {
String word=test.next();
char [] curr=word.toCharArray();
boolean check1=false;
boolean check2=false;
for(int i=0; i<curr.length; i++) {
if(!Character.isLetter(curr[i])) {
check1=true;
System.out.println(check1);
continue;
}
if(check1) {
check2=true;
System.out.println(check2);
break;
}
}
if(!check2) {
System.out.println(word);
}
此逻辑似乎要说的是不打印任何包含非字母字符后接至少一个字母字符的单词。
答案 1 :(得分:-2)
有时甚至连简单的布尔逻辑也很难读懂,但似乎(check1 && !check2)||(!check1 && !check2)
可以归结为!check2
...因此,也许您需要更改该检查的逻辑。