检查输入的数字是否在数组中,否则添加到数组

时间:2015-06-18 18:30:26

标签: java arrays validation input

用户将输入数组的大小及其值。如果输入的值存在,则用户必须输入不同的数字。我似乎无法构造正确的代码来检查插入的值是否存在。

public static void main(String[] args) {
   String holder="", s;
   int size;

   s=JOptionPane.showInputDialog("Enter the size of the array");
   size= Integer.parseInt(s);
   String array1[]= new String[size]; //declared and instantiated array1

   for (int x=0; x<=array1.length-1;x++)
   {
       array1[x]=JOptionPane.showInputDialog("Enter value for array[" +x +"]");


       int a=0;
       if (array1[x].equals(array1[x])){
           a=1;
           JOptionPane.showMessageDialog(null, "exists");
       }
       else
           JOptionPane.showMessageDialog(null, "continue");
   }

   for (int x=0; x<=array1.length-1;x++)
   {
      holder=holder+ "\n"+ array1[x];
   }

    JOptionPane.showMessageDialog(null,holder);

1 个答案:

答案 0 :(得分:0)

这个怎么样?检查值是否存在,否则用户需要重新输入数字。

public static void main(String[] args) {
    String holder = "", s;
    int size;

    s = JOptionPane.showInputDialog("Enter the size of the array");
    size = Integer.parseInt(s);
    String array1[] = new String[size]; //declared and instantiated array1

    for (int x = 0; x <= array1.length - 1; x++) {
        String num = JOptionPane.showInputDialog("Enter value for array[" + x + "]");

        if (Arrays.asList(array1).contains(num)) {
            x = x - 1;
            JOptionPane.showMessageDialog(null, "exists");
        } else {
            array1[x] = num;
            JOptionPane.showMessageDialog(null, "continue");
        }
    }

    for (int x = 0; x <= array1.length - 1; x++) {
        holder = holder + "\n" + array1[x];
    }

    JOptionPane.showMessageDialog(null, holder);
}