使用while循环创建ATM

时间:2019-02-13 08:30:44

标签: java

我在学校有一个创建ATM的项目。我已经做了所有事情,唯一的问题是当用户没有再次输入相同的引脚进行验证时,程序仍然认为该引脚是好的。

代码:

import java.util.Scanner;

public class ValidatePin {

    public static void main(String[] args) {

        Scanner keyboardInput = new Scanner(System.in);
        System.out.println("Enter a new pin between 1 and 9");
        double number = keyboardInput.nextInt();

        while (number == keyboardInput.nextInt()) {
            if (number > 0 && number < 10000) {

            }
            else {
                System.out.println("Error, this pin is not able to use");
            }

            if (number == number) {
                System.out.println("Your pin is verified!");
            }

            if (number != keyboardInput.nextInt()) {
                System.out.println("Error, this pin is not the same!");
            }

        }
    }
}

2 个答案:

答案 0 :(得分:0)

我不清楚您为什么使用while循环。尝试下面的代码,看看这是否是您想要的。

请注意,我已将int用于number1number2。使用double存储整数值毫无意义。

import java.util.Scanner;

public class ValidatePin {

  public static void main(String[] args) {

    Scanner keyboardInput = new Scanner(System.in);
    while (true) {
      System.out.println("\nEnter a new pin between 1 and 9999");
      int number1 = keyboardInput.nextInt();
      if (number1 > 0 && number1 < 10000) {
        System.out.println("Enter the same pin again");
        int number2 = keyboardInput.nextInt();
        if (number1 == number2) {
          System.out.println("Your pin is verified!");
          break;
        }
        else {
          System.out.println("Error, this pin is not the same!");
        }
      }
      else {
        System.out.println("Error, this pin is not able to use");
      }
    }
  }
}

答案 1 :(得分:0)

最好将引脚保持为四位数字,而不是1到10000。在循环运行直到用户第二次提供正确的引脚为止。

    Scanner keyboardInput = new Scanner(System.in);
    System.out.println("Enter a new pin between 1000 and 10000");
    double number1 = keyboardInput.nextInt();
    double number2 = 0;
    boolean bool=true;
    while (bool) {
    number2 = keyboardInput.nextInt();      
    if (number2> 1000 && number2 < 10000) {
         if(number1 == number2){                  
         System.out.println("Your pin is verified!"); 
         bool=false;
         }
         else{
          System.out.println("Please Re-enter the same pin");   
         }  
    }
    else{
    System.out.println("Pin should be between 1000 and 10000"); 
    }
 }