java—如何检查数组中的对象?

368yc8dk  于 2021-07-03  发布在  Java
关注(0)|答案(2)|浏览(375)

我一直在使用这些代码,在用户输入一个他/她想要检查的值是否在数组中时遇到了一个问题。
如何在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);
        }
    }
gev0vcfq

gev0vcfq1#

用途:

b1 = Arrays.asList(Arr1).contains(sInput2);
bvjxkvbb

bvjxkvbb2#

首先你必须初始化 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);

相关问题