当我尝试添加更多代码时,为什么编译器会“在预期时”抱怨?

编写一个包含@字符作为输入的单词的程序。 如果单词不包含@,则应提示用户输入带有@的单词。 一旦读出带有@的单词,它应该输出单词然后终止。

这是我到目前为止所做的:

public class find { public static void main(String[] args) { System.out.println(" Please enter a word with @ "); Scanner scan = new Scanner(System.in); String bad = "@"; String word = scan.next(); do if (!word.contains(bad)) System.out.println(" Please try again "); else System.out.println(" " + word); while (!word.contains(bad)); } } 

我可以在包含“@”的单词作为输入后终止它,但是如果我尝试在“请再试一次”之后将扫描程序添加到该行,它会while expected时说出来。

我认为问题是你缺少do / while的大括号:

  do if (!word.contains( bad )) System.out.println( " Please try again " ); else System.out.println( " " + word); while ( !word.contains( bad )); 

应该:

 do { if (!word.contains( bad )) System.out.println( " Please try again " ); else System.out.println( " " + word); }while ( !word.contains( bad )); 

有些人可能不喜欢这样,但我的建议总是使用开/闭括号。 在这种情况下,代码if / else也是。 它避免了很多混乱。

这就是你的问题所在:

  do if (!word.contains(bad)) System.out.println(" Please try again "); else System.out.println(" " + word); while (!word.contains(bad)); 

你需要从循环开始到结束的位置放置大括号。 |所以这件事应该是:

 do { if (!word.contains(bad)) System.out.println(" Please try again "); else System.out.println(" " + word); } while(!word.contains(bad)); 

为了更好的实践,你应该检查do...while循环。

您的代码的问题是它不会重新读取循环中的单词。 像这样修改你的循环(对代码的最小更改)。

 do { word = scan.next(); if (!word.contains(bad)) System.out.println(" Please try again "); else System.out.println(" " + word); } while (!word.contains(bad)); 

是的,正如其他人指出的那样尝试使用大括号,尤其是嵌套构造。

有两个问题。

  1. 您的代码未正确使用大括号
  2. 如果没有输入正确的单词,您不会尝试阅读新单词。

此外,我更喜欢while循环更好的情况,而不是do-while循环,如下所示。

  Scanner scan = new Scanner ( System.in ); String required= "@"; System.out.println( " Please enter a word with @ " ); String word = scan.next() ; //check if the right word(containing @) is entered, //if not then loop until it is enteres while((!word.contains(required)){ System.out.println( " Please try again " ); //read the new word as input from the user word = scan.next() ; } //right word is entered, display it System.out.println(word); 

另请注意,当您使用scan.next() ,如果输入相同的行,它将分别读取每个单词。