Итак, я должен сделать программу, которая выступает в качестве основного банкомате, и я столкнулся с 2 проблемы:ATM программа метод (возможные логические или скобка ошибки)
- Когда я проверить программу для недействительных паролей с связанная с этим учетная запись, программа должна делать счетчик циклов, который дает пользователю максимум 3 недопустимых попыток, прежде чем он выкинет пользователя, но вместо этого он трижды печатает «Неверный пароль» и заканчивает программу после первого неправильного пароля. Я считаю, что это один брекет ошибка, но я на самом деле не уверен, что сам
И
- Всякий раз, когда я запустил операцию как внесения денег на счет, программа отобразит новую сумму, но фактически не сохранит новое значение для программы. Например, если я ставлю 100 долларов на счет 1, он скажет, что новый баланс составляет 620,36 доллара, но когда он возвращается в главное меню, и я снова проверю новый баланс, и он вернет его обратно к предыдущему значению, которое не предполагается (tjis, где я думаю, логическая ошибка может быть)
Я надеялся, что кто-то сможет направить меня в правильном направлении для любых возможных решений для отладки или общего решения моей ошибки в кодировании.
Это код:
import java.util.*;
public class ATM {
public static Scanner kbd;
private static final int MAXATTEMPTS = 3;
public static void main(String[] args) {
kbd = new Scanner(System.in);
System.out.println("Hello, user. This is an ATM.");
System.out.println("Please enter account number");
String acctNum = kbd.next();
System.out.println("Please enter password");
String pwd = kbd.next();
int attemptNumber = 0;
String res = checkID(acctNum, pwd);
do{
if (res.equals("error")){
attemptNumber++;
System.out.println("Invalid password, please try again.");
if (attemptNumber == MAXATTEMPTS){
System.out.print("Maximum Login Attempts Reached.");
System.exit(0);
}
}
else {
double balance = Double.parseDouble(res);
while(true){
int option = menu();
switch (option) {
case 1:
displayBalance(balance);
break;
case 2:
deposit(balance, balance);
break;
case 3:
withdraw(balance, balance);
break;
case 4:
System.out.println("Thank you for banking with us, have a nice day!");
System.exit(0);
}
}
}
}
while (res.equals("error"));
kbd.close();
}
/**
* Determines if acctNum is a valid account number and pwd is the
* correct password for the account.
* @param acctNum The account number to be tested
* @param pwd The possible password for the account
* @return If the account information is valid, returns the account balance
* as a string. If the account information is invalid, returns the string "error".
*/
public static String checkID(String acctNum, String pwd)
{
String result = "error";
// Strings a, b, and c contain the valid account numbers and passwords.
// For each string, the account number is listed first, followed by
// a space, followed by the password for the account, followed by a space,
// followed by the current balance.
String a = "44567-5 mypassword 520.36";
String b = "1234567-6 anotherpassword 48.20";
String c = "4321-0 betterpassword 96.74";
String acctNum1, acctNum2, acctNum3, pwd1, pwd2, pwd3, bal1, bal2, bal3;
acctNum1 = a.substring(0, a.indexOf(" "));
acctNum2 = b.substring(0, a.indexOf(" "));
acctNum3 = c.substring(0, a.indexOf(" "));
pwd1 = a.substring(a.indexOf(" ")+1, a.lastIndexOf(" "));
pwd2 = b.substring(b.indexOf(" ")+1, b.lastIndexOf(" "));
pwd3 = c.substring(c.indexOf(" ")+1, c.lastIndexOf(" "));
bal1 = a.substring(a.lastIndexOf(" ")+1);
bal2 = b.substring(a.lastIndexOf(" ")+1);
bal3 = c.substring(a.lastIndexOf(" ")+1);
if (acctNum.equals(acctNum1) && pwd.equals(pwd1)){
result = bal1;
}
if (acctNum.equals(acctNum2) && pwd.equals(pwd2)){
result = bal2;
}
if (acctNum.equals(acctNum3) && pwd.equals(pwd3)){
result = bal3;
}
return result;
}
/**
*/
public static int menu(){
boolean invalidInput = true;
do {
System.out.println("Please select from the following options:");
System.out.printf("1. Display Balance \n");
System.out.printf("2. Deposit \n");
System.out.printf("3. Withdraw \n");
System.out.printf("4. Log Out \n");
int choice = kbd.nextInt();
if (choice == 1){
return 1;
}
else {
if (choice == 2){
return 2;
}
else{
if (choice == 3){
return 3;
}
if (choice == 4) {
return 4;
}
}
}
}
while(invalidInput);
return 0;
}
/**
*
* @param accBalance given account balance for Account
* @param depoAmnt amount going to be added to accBalance
* @return double that will show updated balance
*/
public static double deposit(double accBalance, double depoAmnt){
System.out.println("How much would you like to deposit");
depoAmnt = kbd.nextDouble();
double newBalance = accBalance + depoAmnt;
System.out.println("Your new balance is: " + newBalance);
return newBalance;
}
/**
*
* @param accBalance amount of money in account
* @return displays amount of money in account
*/
public static void displayBalance(double accBalance){
System.out.printf("\nYour current balancre is $%.2f\n", accBalance);
}
/**
*
* @param accBalance given account balance for account
* @param withdraw amount to be taken out of account
* @return if withdraw !> accBalance, then it will be subtracted from it and resultant amount will be displayed
*/
public static double withdraw(double accBalance, double withdraw){
System.out.println("How much would you like to withdraw?");
withdraw = kbd.nextDouble();
if (accBalance < withdraw){
System.out.printf("Cannot withdraw more than balance" + "\nYour current balance is: " + accBalance + "\n");
return accBalance;
}
else {
double newBalance = accBalance - withdraw;
System.out.println("Your new balance is: " + newBalance);
return newBalance;
}
}
}
Добро пожаловать в StackOverflow. Пожалуйста, найдите время, чтобы посетить [помощь], а также прочитать [ask]. Вопросы формы «вот мой код, пожалуйста, отлаживайте его» считаются не по теме. StackOverflow не является дискуссионным, учебным или отладочным сайтом. Как это работает, вы должны попытаться решить проблему, а затем обратиться за помощью, когда вы сталкиваетесь с трудностями, четко объясняя, что вы пробовали, и что вы не понимаете. Как минимум, вы должны были пройти через код в отладчике IDE и иметь возможность идентифицировать результаты, которые не соответствуют вашим ожиданиям. –
Вы можете разделить ваш вопрос на 2 части. Но для первого: вы не можете ввести 3 пароля, если вы читаете его только один раз: 'String pwd = kbd.next();'. Вы должны добавить это в цикл. –
рассмотрим использование 'String acctNum = kbd.nextLine();' –