Java 如何检查数组中的对象?

Java 如何检查数组中的对象?,java,arrays,Java,Arrays,我一直在使用这些代码,但在用户输入他/她想要检查的值是否在数组中时,我遇到了一个问题 如何在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

我一直在使用这些代码,但在用户输入他/她想要检查的值是否在数组中时,我遇到了一个问题

如何在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);
        }
    }
publicstaticvoidmain(字符串参数[])
{
字符串sInput1、sInput2、sLetters、s;
int iInput1、i1、i2;
布尔b1=真;
sInput1=JOptionPane.showInputDialog(“在数组中输入值的数目:”);
iInput1=Integer.parseInt(sInput1);
字符串Arr1[]=新字符串[iInput1];
对于(i1=0;i1使用:


首先,您必须将
b1
初始化为
false

boolean b1 = false;
然后您可以进行检查:

for (i1 = 0; i1 < iInput1 && !b1; i1++)
    if (Arr1[i1].equals(sInput2))
        b1 = true;
或者,很快:

JOptionPane.showMessageDialog(null, "The value you want to check is" + (b1 ? " " : " not ") + "in the array.", "RESULT!", JOptionPane.INFORMATION_MESSAGE);

你的问题是什么?你必须搜索整个数组,现在你只能搜索到作为输入的值。除非你的数组被排序,否则这将不起作用。你注意到你问题的标题没有提到任何形式的Swing吗?这是一个很好的暗示,Swing与问题无关,不应该被添加为标记!如果找到搜索的值,您应该添加一个
break
语句。是的,这不会改变复杂性,始终为O(n),但有时可能会有所帮助。但是,我更喜欢以这种方式更改
for
循环中的条件:
for(i1=0;i1
。如果您喜欢“隐藏”在
for
循环中进行额外的检查,然后执行。因为这非常罕见,很容易被忽略。这取决于您的编程风格。
中断
很好,但应尽可能避免。良好编程的规则建议在循环和方法中只有一个入口和出口点。
break很好,但应该尽可能避免。
Cool,所以不是写
break
而是在for循环中写所有出口条件?我肯定,这是非常可读的。但是你是对的,这取决于自己的编程风格,所以没有p我们在这里讨论这个问题。
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);