【问题标题】:Creating new variables with conditional statements in Java在 Java 中使用条件语句创建新变量
【发布时间】:2019-10-28 14:39:11
【问题描述】:

我正在尝试基于比较运算符(三个不同的变量:一个小于,一个大于,一个等于)在 Java 中创建新变量,以检查两年之间两个变量之间的差异

数据分为两年的两类,每年合计100个,如下图:

2018 X=70%        2019 X=20%
2018 Y=30%        2019 Y=80%

我想对 x 和 y 做以下陈述:

  • 如果 x 2019 大于 x 2018,则 new_variable_decrease
  • 如果 x 2019 小于 x 2018,则 new_variable_decrease
  • 如果 x 2019 等于 x 2018,则 new_variable_no_change

我是 Java 新手,但这是我尝试使用 int 和 if 语句设置新变量的方法(我正在使用的程序中没有运行-Q)

int new_variable_increase;
if (x2019 > x2018) {new_variable_increase}

int new_variable_increase;
if (x2019 > x2018) {new_variable_increase}

【问题讨论】:

  • 这些行是相同的。另外,您还没有提出任何问题。
  • 将现有变量名写成语句后,您预计会发生什么?
  • 您的最终目标是能够说,例如,X 类减少了 50%,而 Y 类增加了 50%?

标签: java if-statement conditional-statements


【解决方案1】:

变量的存在(和名称)是静态的,是动态的。如果变量不存在,则无法检查它是否存在,即您的代码无法编译。

听起来您更像是需要一个具有值DECREASEINCREASENO_CHANGEenum,以及该类型的变量,例如

public enum Difference { DECREASE, INCREASE, NO_CHANGE }
Difference diff;
if (x2019 < x2018) {
    diff = Difference.DECREASE;
} else if (x2019 > x2018) {
    diff = Difference.INCREASE;
} else {
    diff = Difference.NO_CHANGE;
}
// use variable here

当然,如果您真的希望局部变量仅在某些条件下存在,请在 ifelse 块内声明该变量:

if (x2019 < x2018) {
    int new_variable_decrease = 0;
    // use variable here
} else if (x2019 > x2018) {
    int new_variable_increase = 0;
    // use variable here
} else {
    int new_variable_no_change = 0;
    // use variable here
}

另一种选择是让所有 3 个变量都存在,但其中只有一个有值,即只有一个不是 null

Integer new_variable_decrease = null;
Integer new_variable_increase = null;
Integer new_variable_no_change = null;
if (x2019 < x2018) {
    new_variable_decrease = 0; // 0 auto-boxed to Integer.ZERO
} else if (x2019 > x2018) {
    new_variable_increase = 0; // 0 auto-boxed to Integer.ZERO
} else {
    new_variable_no_change = 0; // 0 auto-boxed to Integer.ZERO
}
// use all 3 variables here.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-31
    • 2020-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多