我不是很熟悉使用Java的运行总数,因为我最近开始使用它。我必须显示并持有银行余额的总额,出于某种奇怪的原因,它重置为100,这正是我宣布的开始时的情况。有没有办法让我在每次循环时都停止银行余额的重置?Java - 运行总计(使用do while和else else语句)
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int choice, totBal = 0, totWith = 0, totDep = 0;
double with, remBal = 0, deposit, bankBal = 100;
char reply = 0;
do
{
System.out.println("");
System.out.println("Bank online\n");
System.out.println("1. Withdraw");
System.out.println("2. Deposit");
System.out.println("3. Balance");
System.out.println("4. Account Details");
System.out.println("5. Exit\n");
System.out.print("Enter your choice: ");
choice = sc.nextInt();
if(choice == 1)
{
System.out.print("How much do you wish to withdraw?\n");
with = sc.nextInt();
remBal = bankBal - with;
System.out.println("Your new balance is: " + remBal);
totWith++;
}
else if(choice == 2)
{
System.out.print("How much do you wish to deposit?\n");
deposit = sc.nextInt();
remBal = remBal + deposit;
System.out.println("Your new balance is: " + remBal);
totDep++;
}
else if(choice == 3)
{
System.out.println("Your balance is: " + remBal);
totBal++;
}
else if(choice == 4)
{
System.out.println("You made " + totWith + " withdrawls from your account.");
System.out.println("You made " + totDep + " deposits to your account.");
System.out.println("You made " + totBal + " balance checks on your account.");
}
else if(choice == 5)
{
}
System.out.println("");
System.out.print("Do you want to enter another option?(y/n): ");
reply = sc.next().charAt(0);
}while(reply == 'Y' || reply == 'y');
System.out.println("Thank you and goodbye!");
}
}
另外,我觉得我有太多的变数。我怎样才能减少这些?
使用面向对象的方法。 – sturcotte06 2014-10-27 16:21:19
此外,您的totBal将设置为100,因为您在if语句中的任何位置都没有更改它的值,所以您只更改了remBal的值。我会建议使用从开关箱调用的方法来减少变量。 – ryekayo 2014-10-27 16:22:43
尝试实现get/set方法并在循环中使用它们 – Paulquappe 2014-10-27 16:24:36