【问题标题】:How to well adjust a loop in Java?如何在 Java 中很好地调整循环?
【发布时间】:2014-03-24 15:59:03
【问题描述】:

我目前正在编写一个小程序,向用户询问 PinCode,如果 Pin 正确则返回“:)”,如果 Pin 错误则返回“:(”。 我的代码由一个 java 文件和一个文本文件组成。

这是代码:

import java.io.*;
import java.util.*;

public class Main {

static public boolean readPinsData(File dataFile, ArrayList<Integer> data) {
   boolean err = false;
   try {
      Scanner scanner = new Scanner(dataFile);
      String line;
      while (scanner.hasNext()) {
         line = scanner.nextLine();
         try {
            data.add(Integer.parseInt(line));
         } catch (NumberFormatException e) {
            e.printStackTrace();
            err = true;
         }
      }
      scanner.close();
   } catch (FileNotFoundException e) {
      e.printStackTrace();
      err = true;
   }

   return err;
}


public static void main(String[] args) {

    System.out.println("-----------------------");
    System.out.println("MY APP");
    System.out.println("-----------------------");
    Console console = System.console();
    int pinSize = 0;
    int nbTry = 0;

    do{
      do{
    char passwordArray[] = console.readPassword("Enter pin: ");
    pinSize = passwordArray.length;

    if(pinSize != 4){
            System.out.println("Pin must be 4 digits");
        } else {
            System.out.println("Checking...");
        }


   ArrayList<Integer> pins = new ArrayList<Integer>();
   readPinsData(new File("bdd.txt"), pins);
   //System.out.println(pins);
   //System.out.println(passwordArray);


   String[] thePins = new String[pins.size()];
   for (int i = 0; i < thePins.length; i++) {
    thePins[i] = pins.get(i).toString();
}

   String passEntered = String.valueOf(passwordArray);





   for(int i = 0 ; i < thePins.length ; i++){
      if(passEntered.equals(thePins[i]) && pinSize == 4){
          System.out.println(":)");
        } else if(!passEntered.equals(thePins[i]) && pinSize == 4){
            nbTry++;
        }

    }   

  }while(nbTry < 3);
   }while(pinSize != 4);

}
}

这是存储所有好的 Pin 图的 bdd.txt:

1111
2222
3333
4444
5555
6666
7777
8888
9999

实际上我的问题是将尝试次数限制为 3 次。我需要解释一下:

--> 用户必须输入密码

--> 要么他输入一个好的 4 位数密码,然后打印“:)”(应用程序就完成了)

--> 要么他输入了错误的 4 位密码,要么打印出“:(”,并且 nbTry 必须是 ++。 在这种情况下,他只剩下 2 次尝试了

--> 他也可以输入 1 位密码或 2 位密码或 3 位数密码...在这种情况下 nbTry 不受影响,他只需重新输入 4 位数密码。

我不知道如何处理 nbTry 左侧的部分。有什么想法吗?

【问题讨论】:

    标签: java loops for-loop while-loop


    【解决方案1】:

    您希望他只能输入 4 位密码还是希望他能够输入任意长度的密码?

    编辑:

    阅读你的main 我看到你有两个'do...while`。如果您更改它们的顺序,它应该可以工作。我无法在 atm 测试它,因为我在移动位上尝试这样:

    do {
      do {
          ....
      } while (pinSize != 4);
    } while (nbTry < 3);
    

    编辑2:

    boolean loginCorrdect = false;
    for (int i = 0; i < thePins.length; i++) {
       if (passEntered.equals(thePins[i]) && pinSize == 4) {
          System.out.println(":)");
          booleanCorrect = true;
          break;
       } else if (!passEntered.equals(thePins[i]) && pinSize == 4) {
          System.out.println(":(");
       }
    
    }
    if(!booleanCorrect && pinSize == 4){
       nbTry++;
    }
    

    希望您能理解它,因为它很难在移动设备上输入。

    完整的主要代码: public static void main(String[] args) {

    System.out.println("-----------------------");
    System.out.println("MY APP");
    System.out.println("-----------------------");
    Console console = System.console();
    int pinSize = 0;
    int nbTry = 0;
    boolean authenticated = false;
    
    do {
       do {
          char passwordArray[] = console.readPassword("Enter pin: ");
          pinSize = passwordArray.length();
    
          if (pinSize != 4) {
         System.out.println("Pin must be 4 digits");
          } else {
         System.out.println("Checking...");
          }
    
          ArrayList<Integer> pins = new ArrayList<Integer>();
          readPinsData(new File("bdd.txt"), pins);
          // System.out.println(pins);
          // System.out.println(passwordArray);
    
          String[] thePins = new String[pins.size()];
          for (int i = 0; i < thePins.length; i++) {
             thePins[i] = pins.get(i).toString();
          }
    
          String passEntered = String.valueOf(passwordArray);
    
          for (int i = 0; i < thePins.length; i++) {
             if (passEntered.equals(thePins[i]) && pinSize == 4) {
        System.out.println(":)");
        authenticated = true;
        break;
    }
    }
    
    } while (pinSize != 4);
      if (!authenticated && pinSize == 4) {
    System.out.println(":(");
    nbTry++;
     }
    } while (nbTry < 3 && !authenticated);
    }
    

    【讨论】:

    • 这不是答案。请对问题添加评论。
    • 任何长度的别针。如果他输入长度为 到 4 位的 pin,它只会打印“Pin must be 4 digits”,但不会影响尝试次数。仅当输入错误的 4 位密码时才会影响尝试次数
    • 对不起...我不允许这样做 atm 所以我需要将其作为评论提出,然后编辑我的问题以符合目的。
    • 我尝试了您的解决方案,但它不起作用。只有一个错误的引脚后,应用程序停止。我不能要求他再试 2 次​​span>
    • 好的,我遇到了问题...在您的循环中,您提高了尝试次数。您需要像我在帖子中的解决方案一样在循环之外执行此操作。
    【解决方案2】:

    如果我理解您的问题,您可以这样做(完成后您应该关闭()您的扫描仪)-

    static public boolean readPinsData(File dataFile, ArrayList<Integer> data) {
        boolean err = false;
        Scanner scanner = null; // so we can close the Scanner.
        try {
            scanner = new Scanner(dataFile);
            String line;
            while (scanner.hasNext()) {
                line = scanner.nextLine();
                try {
                    data.add(Integer.parseInt(line));
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                    err = true;
                }
                // Limit it to 3 attempts. Set err on 3rd.
                if (data.size() >= 3) {
                    err = true;
                    break;
                }
            }
    
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            err = true;
        } finally {
            if (scanner != null) { // Close the Scanner.
                scanner.close();
            }
        }
    
        return err;
    }
    

    【讨论】:

    • 感谢 Elliott,我已经尝试过您的解决方案,但是这样 4444 或 5555 或不再是好的 Pins... 也许我解释错了。仅在用户输入错误的 4 位密码的情况下,尝试次数必须为 ++。 (我们可以同化为信用卡密码,我们有一个 4 位数的密码,如果我们输入 3 个错误的密码就完成了)
    • @FlorentP 没有。这样只能输入3个pin。将 3 个引脚添加到列表后,它将设置错误标志并结束循环。
    • 我不明白,我尝试了一些好的引脚,但它与我的 bdd.txt 文件不匹配。它到底有什么变化?
    【解决方案3】:

    对您的控制流/逻辑进行自上而下的细化会有所帮助。 由于这有点家庭作业的味道,所以只是一个想法:

    Set<String> pins = readPINs();
    boolean authenticated = false;
    for (int attempt = 0; attempt < 3; ++attempt) {
        String pin = askForPIN();
        if (!isSyntacticalValidPIN(pin)) {
           giveError();
           break;
        } else if (pins.contains{pin)) {
           authenticated = true;
           break;
        }
    }
    if (authenticated) {
        offerMenu();
    }
    

    【讨论】:

    • 谢谢Joop,其实我不需要模拟菜单,我的程序只是基于Pin认证。如果好 --> :) 如果错误 --> :( 就这样,这就是为什么我需要将错误 Pin 的数量限制为 3。
    • 为什么要在!isSyntacticalValidPIN上中断?
    • 是的,我没有准确地写下正确的逻辑;只是举了一个例子,如何开始一个算法的制定。
    猜你喜欢
    • 1970-01-01
    • 2023-03-27
    • 2014-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-15
    • 2013-03-25
    相关资源
    最近更新 更多