java—如何编写while循环

h9vpoimq  于 2021-07-05  发布在  Java
关注(0)|答案(2)|浏览(311)

我目前正在用java制作一个简单的atm程序。我想写一个while循环,当用户输入错误的pin时,它会提示用户再次输入,直到pin匹配为止。当pin匹配时,将显示主菜单。
我自己试过,但不知道怎么修。

while(userPIN != savedPIN)  
    {
     System.out.print("Please enter your correct PIN : ");
     Scanner again = new Scanner(System.in);
     int pass = again.nextInt();
     break;
    }
bf1o4zei

bf1o4zei1#

确定2个错误:
1) 你在测试吗 userPIN != savedPIN 但是你接受这个值变成变量 pass 你什么都不做。
2) 移除第一个循环中的中断,它将始终不循环地退出。
它应该看起来像:

while(pass!= savedPIN)  
    {
     System.out.print("Please enter your correct PIN : ");
     Scanner again = new Scanner(System.in);
     int pass = again.nextInt();
    }
ippsafx7

ippsafx72#

删除“break;”语句并使用新的pin更新userpin,如下所示:

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        int savedPIN = 4444;
        Scanner input = new Scanner(System.in);
        System.out.println("Enter password");
        int userPIN = input.nextInt();
        double withdraw = 0.0, amount = 0.0, deposit = 0.0;

        while (userPIN != savedPIN) {
            System.out.print("Please enter your correct PIN : ");
            Scanner again = new Scanner(System.in);
            userPIN = again.nextInt();
        }

        while (userPIN == savedPIN) {

            System.out.println(" 1 - Inquire Balance \n 2 - Withdraw \n 3 - Deposit \n 0 - Quit ");

            Scanner inputNum = new Scanner(System.in);
            int number = inputNum.nextInt();
            switch (number) {
                case 1:
                    System.out.println("The current balance is $" + amount);
                    break;

                case 2:
                    System.out.println("Enter the amount to withdraw : ");
                    withdraw = input.nextDouble();
                    if (amount >= withdraw) {
                        amount = amount - withdraw;
                        System.out.println("The current balance is $" + amount);
                    } else {
                        System.out.println("Insufficient balance");
                    }
                    break;

                case 3:
                    System.out.println("Enter the amount to deposit : ");
                    deposit = input.nextDouble();
                    amount = amount + deposit;
                    System.out.println("The current balance is $" + amount);
                    break;

                case 0:
                    System.exit(4);
            }

        }

    }
}

相关问题