那么我就在这里想知道是否有办法通过语句传递变量。像这样:
if (a < b) {
double g = 1
} else if (a > b) {
double g = 0
}
if (g = 1) {
System.out.print("true");
} else {
System.out.print("false");
}
主要是说,我想设置一个变量,如果一个语句是真的,转到下一段代码并打印出“true”或“false”,我几乎想知道这是否可行而不创建一种新方法(当然,如果有代码)。 谢谢。
答案 0 :(得分:4)
你快到了。您必须在g
语句之外声明if
,以便您可以在整个函数中访问它。阅读更多关于范围的信息,如果在块{}
中声明一个变量,它就可以在它内部访问,所以当你在if-else if
块中声明它时,你就不能不能在外面访问变量。
同样要比较基本类型(在本例中为double
),您必须使用==
运算符,因为=
用于分配。
double g;
if (a<b) {
g = 1;
}
else if (a>b) {
g = 0;
}
// What happen if 'a = b'?
if (g == 1) {
System.out.print("true");
}
else {
System.out.print("false");
}
注意:如果g
,a == b
需要多少价值?您也可能想要关注这个案例。
答案 1 :(得分:1)
double g;
if (a<b) {
g=1
}
else if (a>b) {
g=0
}
if (g==1) {
System.out.print("true");
}
else {
System.out.print("false");
}
还要确保在if语句中始终使用==
而不是=
答案 2 :(得分:1)
if条件if (g=1)
不适用于java。这适用于C。
你应该编码if (g==1)
来测试g是否实际上等于int值1.
答案 3 :(得分:0)
你有三个问题。
a
和b
未定义。在输入if
声明之前定义它们。g
语句之外定义if
(简单double g;
就足够了),然后将值设置为条件逻辑的一部分。如果您打算将else if
保留在那里, do 必须给它一个默认值,因为Java会抱怨没有定义它。g=1
不会按照你认为应该的方式工作;你可能意思是g == 1
。
使用else if
int a, b; // assumed instantiated with values
double g = -1; // required since Java can't guarantee that the else-if will be hit
if (a<b) {
g = 1;
} else if (a>b) {
g = 0;
}
使用else
int a, b; // assumed instantiated with values
double g; // instantiation not required since Java can guarantee the else case
if (a<b) {
g = 1;
} else {
g = 0;
}
答案 4 :(得分:0)
double g; double a = 4.0; double b = 3.0;
if(a < b){
g = 1.0;
System.out.print("true");
}
else if (a > b){
g = 0.0;
System.out.print("false");
}
// Why not write your code like the above example. It seems like the
//same operations are executed but with less lines of code.