好吧,我的代码可以工作,但是如果用户正确猜测“蓝色”,该行将打印“你得到了正确的颜色!”。然后代码应该结束。然而,它带来了另一个 k.next();线。我怎样才能防止这种情况发生? 如果你不明白,这里是代码。
import java.util.Scanner;
public class BEassignment11
{
public static void main (String [] args)
{
Scanner k = new Scanner (System.in);
String color;
String again;
do
{
System.out.println ("Try to guess my favorite color!");
color = k.next();
if (color.equalsIgnoreCase ("blue"))
{
System.out.println ("You got the right color!");
}
else
System.out.println ("That is not the right color. Would you like to try again? Yes/No");
again = k.next();
}
while (again.equalsIgnoreCase ("yes"));
}
}
最佳答案
您可以使用“break”语句跳出循环,如下所示:
if (color.equalsIgnoreCase ("blue")){
System.out.println ("You got the right color!");
break;
}
关于Java 结束语,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43101431/