如何阻止其他事物的永恒重复?else函数在while(true)循环中永远重复.Java



我想做一个测试代码-确认你不是机器人。我声明了一个名为addauthentication的String变量。接下来,我添加if-else函数。系统会要求你用你的语言写最短的单词(在我的情况下,用亚美尼亚语(。如果addauthentication.equals(//最短的单词(-打印(您已登录帐户!(。

Else("请写下这个词"(。

只要条件为true,使用while循环的if-else函数就会重复。

假设我的答案不正确,那么程序应该向我显示:(请写一个词(。但同样的短语永远存在。但是,如果我的第一个答案是正确的,系统会显示这一点(你已经登录了你的帐户!(——是的,这个想法没有问题。我如何更正我的代码,以便在回答错误后,我可以输入正确的代码,并且短语(请写一个单词(不会重复?

我的代码很轻,似乎不应该有任何错误。特别是,我在StackOverFlow中找不到我的问题的答案,所以我不得不问你我的问题。

import java.util.Scanner;

public class RobotTest2 {
public static void main(String []args) {
String addauthentication;
Scanner obj = new Scanner(System.in);

System.out.println("Confirm with action, that you are not a robot. Write the shortest word in your language.");
addauthentication = obj.next();

while (true) {
if (addauthentication.equals("և")) {
System.out.println("You are logged into your account!");
} else  
System.out.println("Please, write a word.");
}
}   
}

My expected result:
> Confirm with action, that you are not a robot. Write the shortest word in your language.
> 
> // user input "և"
> 
> You are logged into your account!



//other way

> > Confirm with action, that you are not a robot. Write the shortest word in your language.
>     > 
>     > // user input //wrong answer
>     > 
>     > Please write a word. 
>     //user input ("right answer")
>     "You are logged into you account!"

The real result:

>  > Confirm with action, that you are not a robot. Write the shortest word in your language.
>     > 
>     > // user input "և"
>     > 
>     > You are logged into your account!


//Other way

> > >  Confirm with action, that you are not a robot. Write the shortest word in your language.
> >     
> >              //user input 
> >             //wrong answer 
> >             
>              "Please write a word." 
>          "Please write a word." 
>          "Please write a word." 
>          "Please write a word." 
>          "Please write a word." 
>          "Please write a word." 
>         ......
//And so, the same phrase repeats forever.

好的,所以如果我理解得很好,你想一直呆在循环中,直到用户给出正确的答案。你不想;请写一个字";永远展示。之所以会发生这种情况,是因为你只从控制台读取一次(在循环之外(,所以完全相同的字符串会一次又一次地求值,如果第一次出错,它就会一直出错。所以我的建议是在循环中阅读,这样你就会在每次迭代中检查答案。

while (true) {
addauthentication = obj.next();
if (addauthentication.equals("և")){
System.out.println("You are logged into your account!");
break;
}
else{
System.out.println("Please, write a word.");
}
}

正如您所看到的,我添加了一个break,以便在用户找到正确答案时退出循环。

最新更新