gpt4 book ai didi

java - 这是初始化变量的正确方法吗

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

在使用之前将 newWeight 设置为 0.0(在 switch block 之前)是一种不好的做法吗?如果我只是声明它,我会在编译器中收到一个错误,指出变量 newWeight 可能尚未初始化。

import java.util.*;

public class SpaceBoxing {
public static void main(String[] args){
Scanner s = new Scanner(System.in);
System.out.print("Please enter your current weight ");
float weight = s.nextFloat();

System.out.println("I have information on the following planets");
System.out.println("1. Venus 2. Mars 3. Jupiter");
System.out.println("4. Saturn 5. Uranus 6. Neptune");
System.out.println(" ");
System.out.println("Which planet are you visiting");

int planet = s.nextInt();
double newWeight = 0.0;

switch(planet){
case 1:
newWeight = weight*0.78;
break;
case 2:
newWeight = weight*0.39;
break;
case 3:
newWeight = weight*2.56;
break;
case 4:
newWeight = weight*1.17;
break;
case 5:
newWeight = weight*1.05;
break;
case 6:
newWeight = weight*1.23;
break;
}
System.out.println("Your weight would be " + newWeight + " pounds on that planet");
}
}

最佳答案

您不需要在切换之前实例化它,但您应该在 switch 中包含一个 default 情况,在其中分配一个值或抛出一个 异常。如果前面的情况未涵盖提供的参数,则将执行默认情况。

int planet = s.nextInt();
double newWeight;

switch(planet){
case 1:
newWeight = weight*0.78;
break;
case 2:
newWeight = weight*0.39;
break;
case 3:
newWeight = weight*2.56;
break;
case 4:
newWeight = weight*1.17;
break;
case 5:
newWeight = weight*1.05;
break;
case 6:
newWeight = weight*1.23;
break;
default:
newWeight = 0.0;
// or
throw new IllegalArgumentException();
}

关于java - 这是初始化变量的正确方法吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22119305/

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