【发布时间】:2015-04-06 08:02:55
【问题描述】:
我对 Java 还很陌生,并且正在从一本书中学习。我刚刚在书中了解了强制转换类型和布尔值/逻辑运算符,我遇到了挑战。一个带有真假值的逻辑运算符表程序,我必须对其进行调整,使其显示 1 和 0 而不是真假,所以我想出了这个:
/* Project 2-2: a truth table for the logical operators.
show 1 en 0 ipv true en false.
*/
class LogicalOpTableSimon {
public static void main(String args[]) {
int p, q;
System.out.println("P\tQ\tAND\tOR\tXOR\tNOT");
p = 1; q = 1;
System.out.print(p + "\t" + q +"\t");
System.out.print(p + "\t" + q + "\t");
p = 0;
System.out.println(p + "\t" + p);
p = 1; q = 0;
System.out.print(p + "\t" + q +"\t");
System.out.print(q + "\t" + p + "\t");
System.out.println(p + "\t" + q);
p = 0; q = 1;
System.out.print(p + "\t" + q +"\t");
System.out.print(p + "\t" + q + "\t");
System.out.println(q + "\t" + q);
p = 0; q = 0;
System.out.print(p + "\t" + q +"\t");
System.out.print(p + "\t" + q + "\t");
p = 1; q = 0;
System.out.println(q + "\t" + p);
}
}
这工作正常,表格显示正确的值。但是,我想知道,因为我刚刚在书中学习了如何转换或转换不同的类型,所以挑战是否意味着使用它?换句话说,我可以使用强制转换/转换来获得相同的结果吗?我尝试了不同的东西,但没有奏效。或者,也许我认为很难。感谢您提供的任何提示:)。对了,原代码是:
// Project 2-2: a truth table for the logical operators.
class LogicalOpTable {
public static void main(String args[]) {
boolean p, q;
System.out.println("P\tQ\tAND\tOR\tXOR\tNOT");
p = true; q = true;
System.out.print(p + "\t" + q +"\t");
System.out.print((p&q) + "\t" + (p|q) + "\t");
System.out.println((p^q) + "\t" + (!p));
p = true; q = false;
System.out.print(p + "\t" + q +"\t");
System.out.print((p&q) + "\t" + (p|q) + "\t");
System.out.println((p^q) + "\t" + (!p));
p = false; q = true;
System.out.print(p + "\t" + q +"\t");
System.out.print((p&q) + "\t" + (p|q) + "\t");
System.out.println((p^q) + "\t" + (!p));
p = false; q = false;
System.out.print(p + "\t" + q +"\t");
System.out.print((p&q) + "\t" + (p|q) + "\t");
System.out.println((p^q) + "\t" + (!p));
}
}
我在互联网上搜索并在书中阅读了更多内容。但我找不到铸造版本或类似的东西。
【问题讨论】:
-
您不能在 Java 中将
boolean强制转换为int。相反,请考虑使用if-else语句来显示适当的值。 -
int value = (boolean) ? 1 : 0; -
那么,如果我理解正确的话,你需要为每个假值显示 0,为每个真值显示 1?为什么不创建一个方法
toInteger(boolean b),并为您显示的每个布尔值调用它?