gpt4 book ai didi

Java Scanner/Input Help(输入不匹配异常)

转载 作者:行者123 更新时间:2023-12-01 22:06:04 24 4
gpt4 key购买 nike

atm 程序。当您按数字时,它会将您重定向到一个选项。前任。 2 = 存款。它要求提取金额或按“b”进入主菜单。如果您输入存款金额,则可以正常工作。如果按“b”进入主菜单,它将不起作用并发送输入不匹配异常

static double balance = 0.0;
public static void deposit(double amount)
{
balance = balance + amount;
}

public static void withdraw(double amount)
{
balance = balance - amount;
}


private static void transaction()
{
Scanner input = new Scanner(System.in);
System.out.println("Welcome to the ATM");
System.out.println("1 for balance\n2 for deposit\n3 for withdraw");
int choice = input.nextInt();
switch (choice) {
case 1:
System.out.println("Your balance is " + balance);

transaction();
case 2:
System.out.println("Enter the amount or 'b' to go back");
if (input.nextLine() == "b")
{
transaction();
}
else
{
deposit(input.nextDouble());
System.out.println("Success!");
transaction();
}***
case 3:
if (balance >= 0)
{
System.out.println("Your balance is negative!");
}
else
{
System.out.println("Enter the amount");
withdraw(input.nextDouble());
System.out.println("Success!");
transaction();
}
default:
System.out.println("Enter a valid option");
transaction();
}
}

最佳答案

使用 .quals() 而不是 == 进行相等性检查 -

input.nextLine().equals("b")

奖金建议:

您不应直接在 if() 内获取输入,而应首先将用户输入作为 String 获取。然后检查它的 b 是否,否则将其转换为 double 并存入!

String userInput = input.next();

if (userInput.equals("b")) {
transaction();
} else {
try {
double depositAmount = Double.parseDouble(userInput);
deposit(depositAmount);
} catch (NumberFormatException ex) {
System.out.println("Invalid input");
}
}

关于Java Scanner/Input Help(输入不匹配异常),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58687261/

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