我试着从这本 Java 书的开头开始阅读,并为暑假做一些练习。我想出了这个问题:“ (信用额度计算器)开发一个Java应用程序,确定几个百货商店客户中的任何一个是否超过了收费帐户的信用额度......对于那些信用额度被超过的客户,程序应显示消息“超出信用额度”。
我的代码只有在我使用 Charge to Credit ONCE 时才有效。如果我再次使用 Charge to Credit,我的新余额值将会改变。例子:
* Acc # = 123 * Beginning Balance = 20000 * Credit Limit = 25000 * Select Transaction = 1 (Charge to Credit) * Amount to charge = 4000 * Select Transaction = 2 (Pay credit) * Amount to pay = 2000 [My balance should now be 22000) * Select Transaction = 1 (Charge to Credit) * Amount to charge = 10000 [This shud exceed credit limit] * Select Transaction = 3 (Balance Inquiry) * My new balance is now 18000
这是我现在的问题。我的新余额应该仍然是 22000,因为信用额度已经超过了。但现在是 18000。我不知道哪里出了问题,所以我需要帮助,拜托。
所以这是我的代码:
客户.java
import java.util.Scanner;
public class Customer {
Scanner input = new Scanner (System.in);
int accNum,
beginBal,
creditLimit;
int itemsCharged,
creditsPaid,
newBalance;
int transaction;
String action;
public void start (){
System.out.print("\nAccount Number: ");
accNum = input.nextInt();
System.out.print("Beginning Balance: ");
beginBal = input.nextInt();
System.out.print("Credit Limit: ");
creditLimit = input.nextInt();
transaction();
}
public void transaction (){
boolean loop = true;
while (loop){
System.out.println("\n[1] Charge to Credit \n[2] Pay Credit \n[3] Balance Inquiry/Exit");
System.out.print("Select Transaction #: ");
transaction = input.nextInt();
switch (transaction){
case 1:
System.out.print("\n--CHARGE TO CREDIT-- \nEnter amount: ");
itemsCharged = input.nextInt();
newBalance = beginBal + itemsCharged - creditsPaid;
if (newBalance > creditLimit){
System.err.println("Credit Limit Exceeded!");
newBalance -= itemsCharged;
} else {
System.out.println("Amount charged.");
}
break;
case 2:
System.out.print("\n--PAY CREDIT-- \nEnter amount: ");
creditsPaid = input.nextInt();
newBalance = beginBal + itemsCharged - creditsPaid;
if (creditsPaid > newBalance){
System.err.println("Invalid Amount!");
newBalance -= creditsPaid;
} else {
System.out.println("Payment posted!");
newBalance = beginBal + itemsCharged - creditsPaid;
}
break;
case 3:
System.out.println("\n--BALANCE INQUIRY-- \nNew Balance: " + newBalance);
restart();
break;
default:
System.err.println("Invalid number!");
transaction();
break;
}
}
}
public void restart (){
System.out.println("\nDo you have another transaction? [Y/N]");
System.out.print("Select Action: ");
boolean loop = true;
while (loop){
action = input.nextLine();
switch (action){
case "Y":
start();
break;
case "N":
System.err.println("Terminated.");
System.exit(0);
break;
}
}
}
} // end class
CreditLimitCal.java
public class CreditLimitCal {
public static void main (String[] args){
Customer cus = new Customer();
cus.start();
}
}