有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

我想做一个测试代码-确认你不是机器人。 我声明了一个名为addauthentication的字符串变量。 接下来,我添加if-else函数。系统将要求您用您的语言书写最短的单词(在我的例子中,是亚美尼亚语)。如果添加身份验证。等于(//最短的单词)-打印(您已登录到您的帐户!)

否则 (“请写下这个词”)

只要条件为真,使用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.

共 (1) 个答案

  1. # 1 楼答案

    好的,如果我理解得很好的话,你希望在用户给出正确答案之前保持循环。你不想“请写一个字”永远被展示出来。 发生这种情况的原因是,您只从控制台读取了一次(在循环之外),因此完全相同的字符串会反复计算,如果第一次出错,它会一直出错。 所以我的建议是阅读循环内部的内容,这样你就可以在每次迭代中检查答案

    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,以便在用户点击正确答案时退出循环