【问题标题】:condition inside another in JAVAJAVA中另一个内部的条件
【发布时间】:2019-10-06 14:10:00
【问题描述】:

let the user get 3 attempts only, after it he get his account suspened我尝试要求用户提供 3 次最终密码,如果他不这样做,他的帐户会被暂停,如果正确,他会收到一条令人讨厌的消息。


package EE;
import java.util.Scanner;
public class test {
    public static void main(String[] args) {
            final String password= "Test";
            Scanner sc = new Scanner(System.in);
            System.out.println("Please enter the password: ");
            String pass = sc.next();
            for (int i=0; i<2;) {
            if (!pass.equals (password))
                i++;
                System.out.println("Try again! ");
                String pass1 = sc.next();
                     if(pass.equals( password))
                        System.out.println("Welcome");
                        String pass2 = sc.next();
                    if (i == 2)
            System.out.println("Sorry, your account is suspened");      
    }
}}

【问题讨论】:

  • 你问的问题是什么?
  • 使用一个循环,一个while循环。查找并试一试。
  • 尝试在 if 语句中使用方括号 { }。如果你没有,它只会执行 if 语句之后的下一行
  • @alea 你能说得更具体些吗?谢谢!

标签: java eclipse if-statement netbeans user-input


【解决方案1】:

正如 Alea 所说,您需要在 if 语句中的块周围使用大括号 { ... }

for (int i=0; i<2;) {
if (!pass.equals (password))
    i++;
    System.out.println("Try again! ");
    String pass1 = sc.next();
         if(pass.equals( password))
            System.out.println("Welcome");
            String pass2 = sc.next();
        if (i == 2)
System.out.println("Sorry, your account is suspened");
} 

其实是这个意思:

for (int i = 0; i < 2; ) {
    if (!pass.equals(password)) {
        i++;
    }
    System.out.println("Try again! ");
    String pass1 = sc.next();
    if (pass.equals(password)) {
        System.out.println("Welcome");
    }
    String pass2 = sc.next();
    if (i == 2) {
        System.out.println("Sorry, your account is suspened");
    }
}

一旦我们正确缩进代码并在编译器期望的位置添加大括号,我们就可以开始看到一些问题了。

例如:

  1. 当密码正确时,i 不会增加任何内容。这意味着i &lt; 2 不会是真的,并且循环将继续循环。

  2. 您在每次循环迭代中调用了两次next()

等等。

现在我可以为你重写你的代码1。但你不会从中学到很多东西。 (通过为自己编写代码、犯错误、发现并纠正错误……您自己会学得最好!)

相反,我将向您推荐阅读Rubber Duck debugging 技术。这听起来像是一个笑话,但事实并非如此。这是一种以幽默方式解释的重要技术。这就是我在 18 岁时学习编程时所教的调试程序的方法2

Rubber Duck 调试背后的想法是帮助您了解计算机如何“思考”。一旦你能做到这一点,编程就会变得容易得多。这就是为什么我强烈建议你自己做这个!

无论如何,一旦您可以想象代码做错了什么,那么下一步就是弄清楚它应该做什么


1 - 一开始会更快!

2 - 虽然我们当时没有用那个名字来称呼它。我们称之为手工执行,我们用铅笔和纸来做。一般在旧电脑打印输出的背面。是的,很久以前。在那些日子里,我们没有调试器或 IDE。这是打卡和等待 20 分钟才能得到打印输出!

【讨论】:

  • 谢谢,我解决了这个问题,就像你和@alea 说的,大括号。
猜你喜欢
  • 2020-02-11
  • 2015-11-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-16
相关资源
最近更新 更多