【发布时间】:2020-07-28 13:28:57
【问题描述】:
我想做一个测试代码 - 确认你不是机器人。 我声明了一个名为 addauthentication 的字符串变量。 接下来,我添加 if else 函数。系统会要求你用你的语言写最短的单词(在我的例子中是亚美尼亚语)。 if addauthentication.equals(// 最短的单词) - 打印(您已登录到您的帐户!)。
其他 (“请写下单词”)。
只要条件为真,使用 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.
【问题讨论】:
-
当
if条件为真时,您忘记了循环中的break。 -
顺便说一句:“我的代码很轻,看起来应该没有任何错误。”简短并不意味着正确。
-
另外,请参阅this question,了解如何询问输入直到正确为止。
-
只在 while 内执行
addauthentication = obj.next();,在 if-then 部分执行break。太轻的代码也是……
标签: java loops if-statement