我一直在使用这些代码,当用户输入他/她想要检查它是否在数组中的值时,我在部件中遇到了问题。
如何用Java检查数组中的对象?
public static void main (String args [])
{
String sInput1,sInput2,sLetters,s;
int iInput1,i1,i2;
boolean b1 = true;
sInput1 = JOptionPane.showInputDialog("Enter the number of values in the array:");
iInput1 = Integer.parseInt (sInput1);
String Arr1[] = new String [iInput1];
for (i1=0;i1<iInput1;i1++)
{
Arr1[i1] = JOptionPane.showInputDialog("Enter the values:");
System.out.println("You entered " + Arr1[i1] + ".");
}
sInput2 = JOptionPane.showInputDialog("Enter the value you want to check in the array:");
for (i1=0;i1<iInput1;i1++)
{
if (Arr1[i1].equals(sInput2))
{
b1=true;
}
else
{
b1=false;
}
if (b1 == true)
{
JOptionPane.showMessageDialog(null,"The value you want to check is in the array.","RESULT!",JOptionPane.INFORMATION_MESSAGE);
}
else
{
JOptionPane.showMessageDialog(null,"The value you want to check is not in the array.","RESULT!",JOptionPane.INFORMATION_MESSAGE);
}
}
答案 0 :(得分:0)
使用:
b1 = Arrays.asList(Arr1).contains(sInput2);
答案 1 :(得分:0)
首先,您必须将b1
初始化为false
:
boolean b1 = false;
然后你可以做检查:
for (i1 = 0; i1 < iInput1 && !b1; i1++)
if (Arr1[i1].equals(sInput2))
b1 = true;
最后,打印出结果:
if (b1)
JOptionPane.showMessageDialog(null, "The value you want to check is in the array.", "RESULT!", JOptionPane.INFORMATION_MESSAGE);
else
JOptionPane.showMessageDialog(null, "The value you want to check is not in the array.", "RESULT!", JOptionPane.INFORMATION_MESSAGE);
或者,很快:
JOptionPane.showMessageDialog(null, "The value you want to check is" + (b1 ? " " : " not ") + "in the array.", "RESULT!", JOptionPane.INFORMATION_MESSAGE);