Java 我怎样才能替换;“真的”;及;假;在爪哇?
我需要更改布尔变量的值,例如: 更改此项:Java 我怎样才能替换;“真的”;及;假;在爪哇?,java,replace,boolean,Java,Replace,Boolean,我需要更改布尔变量的值,例如: 更改此项: boolean x = true; System.out.print(x); //console: true 为此: boolean x = true; System.out.print(x); //console: 1 这是我的代码: final boolean[] BOOLEAN_VALUES = new boolean [] {true,false}; for (boolean a : BOOLEAN_VALUES) {
boolean x = true;
System.out.print(x); //console: true
为此:
boolean x = true;
System.out.print(x); //console: 1
这是我的代码:
final boolean[] BOOLEAN_VALUES = new boolean [] {true,false};
for (boolean a : BOOLEAN_VALUES) {
boolean x = negation(a);
String chain = a+"\t"+x;
chain.replaceAll("true", "1").replaceAll("false","0");
System.out.println(chain);
}
negation is a method:
public static boolean negation(boolean a){
return !a;
}
如您所见,我尝试使用.replaceAll
,但它不起作用,当我执行时,这是输出:
我真的没有看到我的错误。System.out.println(x?1:0)应该做到这一点,如果为真,基本上为1,否则为0。有两种方法:
if-else
one,用于检查x
是否为true
或false
if (x) {
System.out.println(1);
} else {
System.out.println(0);
}
注意:如果(x)
与如果(x==true)
相同
三元模型:
System.out.println(x ? 1 : 0);
它检查
x
是否为true
如果是,则打印1
,否则打印0
。我建议使用三元变量,因为它较短,有助于代码的清晰。现在我找到了解决方案,只是没有匹配变量:
chain = chain.replaceAll("true", "1").replaceAll("false","0");
现在问题解决了,谢谢你的回答。
x=!x
x=false
?我没听懂你的意思,但是如果你说的是打印“1”而不是打印“true”,你可以使用这样的东西:System.out.print(x?1:0)代码>System.out.println(x?1:0)代码>?可能与hmm重复我找到了解决方案,只是缺少一行:[code]chain=chain.replaceAll(“true”,“1”).replaceAll(“false”,“0”);[/code]
chain = chain.replaceAll("true", "1").replaceAll("false","0");