![](/img/trans.png)
[英]How can I make a java program to understand the user-input “t” as “true” and “f” as “false”(boolean)?
[英]How can I replace “true” and “false” in java?
我需要更改布爾變量的值,例如:
改變這個:
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
,但它不起作用,當我執行時,這是輸出:
a ¬a ---------------- true false false true
我真的沒有看到我的錯誤。
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);
}
注意: if (x)
與if (x == true)
。
三元一:
System.out.println(x ? 1 : 0);
檢查x
是否為true
如果是,則打印1
否則打印0
。 我建議三元一個,因為它更短,有助於代碼清晰。
現在我找到了解決方案,我只是錯過了匹配變量:
chain = chain.replaceAll("true", "1").replaceAll("false","0");
現在這已經解決了,謝謝你的答案。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.