gpt4 book ai didi

java - Java ATM 项目中使用 If 语句进行切换

转载 作者:行者123 更新时间:2023-11-30 07:51:56 25 4
gpt4 key购买 nike

现在我正在开发一个 ATM 项目。用户将输入姓名、余额、交易类型和交易金额。交易类型为提款(W)存款(D)R(报告),我使用的是switch,有 3 个案例 WDR。如果您出现以下情况,程序将输出错误: 输入错误的代码、您没有足够的资金来执行您选择的交易类型、以及您输入的金额为负数。现在,我在尝试设置开关时遇到了困难。我的代码如下,任何帮助将不胜感激!谢谢

import java.io.*;
import java.util.*;
public class atmValidator {

public static void main(String[] args) {

String fname = " ", lname = " ";

double balbefore = 0.0, balafter = 0.0, transamount = 0.0;

char code = ' ';

Scanner screen = null;
FileInputStream fis = null;
FileOutputStream fos = null;
PrintWriter pw = null;

//Declaring the variables/scanner/etc.

try {
fis = new FileInputStream ("transactions.txt");
fos = new FileOutputStream ("statement.txt");

screen = new Scanner (fis);
pw = new PrintWriter (fos);

} catch (FileNotFoundException e) {
System.out.println("File not found");
System.exit(0);
}

//The try/catch for reading from the file

while (screen.hasNext()) {
fname = screen.next();
lname = screen.next();
balbefore = screen.nextDouble();
code = screen.next().charAt(0);
transamount = screen.nextInt();

//A while loop to gather the info from the file, and the variables getting their values from the files.

switch (code) {

case 'D':
balafter = balbefore + transamount;
if (transamount <0) {
pw.println("ERROR: Enter positive amount.");
}
else if (balafter < 300) {
pw.println("Warning, balance below $300");
}

{

// Where I am stuck at :(
}
}
}
screen.close();
pw.close();

}
}
//Sorry for the weird braces and spaces

最佳答案

您可以在 switch 主体中编写如下情况。您可以进一步延长条件,但在这里我只是给您举了一个示例。如果字符不是D、W或R,则执行default case。

    switch (code) {
case 'D':
balafter = balbefore + transamount;
System.out.println("");
if (balafter < 0) {
pw.println("Insufficent funds");

} else if (balafter < 300) {
pw.println("Warning, balance below $300");
}else{
pw.println("Well. You have now " + balafter + "$");
}
break;
case 'W':
balafter = balbefore - transamount;
if (transamount > balbefore) {
pw.println("Sorry. You don't enough funds.");

} else if (transamount <= balbefore && balafter < 300) {
pw.println("Warning, balance below $300");
} else {
pw.println("The withdrawl was successful.");
}
break;
case 'R':
balafter = balbefore + transamount;
if (balafter < 0) {
pw.println("Insufficent funds");

} else if (balafter < 300) {
pw.println("Warning, balance below $300");
} else {
pw.println("Good. Your balance is " + balAfter);
}
break;
default:
System.out.println("Nothing to do.");
break;
}

关于java - Java ATM 项目中使用 If 语句进行切换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33239679/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com