java-将布尔值更改为yes no
我有一个布尔数组,需要稍后向用户显示,而不是显示true或false。我想显示yes或no。有人能帮我吗java-将布尔值更改为yes no,java,swing,boolean,Java,Swing,Boolean,我有一个布尔数组,需要稍后向用户显示,而不是显示true或false。我想显示yes或no。有人能帮我吗 public static boolean[] seen (boolean[] birds) { String quit = "100"; String ans = ""; while(!ans.equals(quit)) { ans=JOptionPane.showInputDialog(null,"Which bir
public static boolean[] seen (boolean[] birds)
{ String quit = "100";
String ans = "";
while(!ans.equals(quit))
{ ans=JOptionPane.showInputDialog(null,"Which bird are you reporting? \n 1) Blue Tit\n 2) Blackbird\n 3) Robin\n 4) Wren\n 5) Greenfinch");
if (ans.equals("1"))
{ birds[0]=true;
}
else if (ans.equals("2"))
{ birds[1]=true;
}
else if (ans.equals("3"))
{ birds[2]=true;
}
else if (ans.equals("4"))
{ birds[3]=true;
}
else if (ans.equals("5"))
{ birds[4]=true;
}
}
return birds;
}
public static void display(boolean[] newbirds)
{ JOptionPane.showMessageDialog(null,"newbirds[0]+" "+newbirds[1]+" "+newbirds[2]+" "+newbirds[3]+" "+ newbirds[4]+"");
}
}
我希望数组newbird[I]显示为yes或no格式,有人能帮忙吗?您可以为它定义一个类似这样的方法
// Use ternary operator :
String yesOrNo = condition?result1:result2
// so if condition is true the returned value will be result1 else it will be result2.
JOptionPane.showMessageDialog(null, newbirds[0]?"Yes":"No"+" "+newbirds[1]?"Yes":"No"+" "+newbirds[2]?"Yes":"No"+" "+newbirds[3]?"Yes":"No"+" "+ newbirds[4]?"Yes":"No");
// or you can make a method to get the value.
String yesOrNo(boolean b){
return b?"Yes":"No";
}
//use it like
JOptionPane.showMessageDialog(null,yesOrNo(newbirds[index]));
public String booleanToString(boolean b) {
return b ? "yes" : "no";
}
我上面使用的是三元运算符。
它的工作原理如下:
boolean (expression) ? actionIfTrue : actionIfFalse
if (b)
return "yes";
else
return "no";
boolean a = false;
boolean b = !a;
// etc
someMethod( booleanToString(a) + " xyz " + booleanToString(b) );
第一部分我觉得很简单。它只是任何表达式、变量或任何布尔值或布尔值的对象。例如a==b
或true
第二部分是actionIfTrue
它仅在表达式为true
时调用。
第三部分是actionIfFalse
它仅在表达式为false
时调用
它的工作原理类似于缩短的if
。上述if
语句如下所示:
boolean (expression) ? actionIfTrue : actionIfFalse
if (b)
return "yes";
else
return "no";
boolean a = false;
boolean b = !a;
// etc
someMethod( booleanToString(a) + " xyz " + booleanToString(b) );
像这样使用它:
boolean (expression) ? actionIfTrue : actionIfFalse
if (b)
return "yes";
else
return "no";
boolean a = false;
boolean b = !a;
// etc
someMethod( booleanToString(a) + " xyz " + booleanToString(b) );
这可用于在阵列上循环并打印“是”或“否”:
你可以使用ApacheComons 从字符串到布尔值
BooleanUtils.toBooleanObject(string)
从布尔到字符串
BooleanUtils.toString(boolVal,"Yes","No")
对于“组中的1”,最好使用按钮组中的单选按钮、单个选择列表、组合框或微调器或..下一步要添加的内容是
StringBuilder
逐位创建字符串,并向字符串生成器添加循环(为每个数组值调用booleanToString
)。更加优雅和适应性更强(例如,对于不同的数组大小)。虽然这可能回答了这个问题,但它没有提供上下文来解释建议的更改。编辑你的答案,包括对你所写内容的解释。请在/
之后写评论,以免阅读时混淆。