gpt4 book ai didi

java - Java 在 if/else 语句中返回多个值

转载 作者:行者123 更新时间:2023-12-01 22:40:00 25 4
gpt4 key购买 nike

我很难理解如何根据多种情况准确返回一个值。如果我选择return kg;来 self 的readWeight()方法,在 if 语句之外,错误告诉我 kg可能尚未初始化。它不是在我的 if 语句中初始化的吗?有人能准确地告诉我我做错了什么吗?我真的很想明白这一点。谢谢大家,真的很感激。

public static void main(String[] args) {
double kg = readWeight();
System.out.println("Your dog weighs" + kg) ;
System.out.println("Completed computing Kay9 Kibbles amount.") ;
}//end of main method

public static double convertLBtoKG(double lb) {
final double KG_TO_LB_CONVERSION = 0.454 ;
double kg = lb * KG_TO_LB_CONVERSION ;
return kg ;
}//end of convertLBtoKG method

public static double readWeight(){
Scanner keyboard = new Scanner(System.in) ;
System.out.println("Would you like to enter your dog's weight " +
"in kilograms (kg) or pounds (lb)?\n" +
"Enter k (for kg) or p (for lb):") ;
char weight = keyboard.nextLine().charAt(0) ;
double lb;
double kg;

if(weight == 'p' ){
System.out.println("Enter your dog's weight in lb:") ;
lb = keyboard.nextDouble() ;
kg = convertLBtoKG(lb) ;
}

else if(weight == 'k'){
System.out.println("Enter your dog's weight in kg:") ;
kg = keyboard.nextDouble() ;
}

else if(weight != 'p' && weight != 'k'){
System.out.println("I can't understand your choice; assuming kilograms.") ;
System.out.println("Enter your dog's weight in kg:") ;
kg = keyboard.nextDouble() ;
}
return kg ;
}

最佳答案

只需将其初始化为某个默认值:

double kg = 0.0;

局部变量必须被初始化,即使它看起来至少有一个 if 语句总是为 true,并且 kg 将在相应的 block 内初始化,编译器可能不会足够聪明地意识到这一点。

另一个可能有效的选项是将最后一个“else if”替换为“else”。

关于java - Java 在 if/else 语句中返回多个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26314708/

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