gpt4 book ai didi

java - Dr Java 代码错误

转载 作者:行者123 更新时间:2023-12-01 18:42:32 24 4
gpt4 key购买 nike

这表明我的局部变量newaccbalance可能尚未初始化。我知道我将其声明为 double 。请帮忙

 import java.util.*;

public class Pg244Problem12 {

public static void main(String[] args)
{

int accnum, minbalance, currentbalance;
int acctype;
double newaccbalance;

Scanner console = new Scanner(System.in);



System.out.println("Enter the customer's account number:");
accnum = console.nextInt();
System.out.println("Enter the customer's account type by using the number 1 for Checking or 2 for Savings:");
acctype = console.nextInt();
System.out.println("Enter the minimum balance the customer's account can have:");
minbalance = console.nextInt();
System.out.println("Enter the current balance of the customer's account:");
currentbalance = console.nextInt();



// Checkings
if(acctype == 1 && currentbalance >= (minbalance+5000)){
newaccbalance = ((currentbalance*.05)*(1/12));
}
if (acctype == 1 && currentbalance >= minbalance && currentbalance < (minbalance+5000)){
newaccbalance = ((currentbalance*.03)*(1/12));
}
if (acctype == 1 && currentbalance < minbalance){
newaccbalance = (currentbalance-25);
}

// Savings
if (acctype == 2 && currentbalance >= minbalance){
newaccbalance = ((currentbalance*.04)*(1/12));
}
if (acctype == 2 && currentbalance < minbalance){
newaccbalance = (currentbalance - 10);
}



System.out.println("The account number is: "+ accnum);
System.out.println("The account type is: "+ acctype);
System.out.println("The current balance is: "+ currentbalance);
System.out.println("The new account balance is: "+ newaccbalance);

}
}

最佳答案

首先,声明和初始化不是一回事。

double newaccbalance; 声明变量。

newaccbalance = 42; 正在初始化变量。

代码中的问题是编译器无法保证任何 if 语句均为 true,因此 newaccbalance 可能未初始化。

我建议两件事:

首先,将变量初始化为默认值,double newaccbalance = 0; 将声明并初始化该变量。

其次,更改 if 语句的结构并使用 if-else-if,如下所示:

if (acctype == 1) {
// For these if statements, acctype is 1 so we don't need to check that again
if(currentbalance >= (minbalance+5000)){
newaccbalance = ((currentbalance*.05)*(1/12));
}
else if (currentbalance >= minbalance) {
// && currentbalance < (minbalance+5000) will be true because the above if-statement is **not** true
newaccbalance = ((currentbalance*.03)*(1/12));
}
else {
// if (acctype == 1 && currentbalance < minbalance) would always be true here
newaccbalance = (currentbalance-25);
}
}
else if (acctype == 2){
// Savings
if (currentbalance >= minbalance) {
newaccbalance = ((currentbalance*.04)*(1/12));
}
else { // currentbalance < minbalance) is always true here
newaccbalance = (currentbalance - 10);
}
}
else {
// acctype is neither 1 or 2, what should we do now? RuntimeError, Catastrophic failure, the monsters are coming! We're screwed!
}

关于java - Dr Java 代码错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19338954/

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