简体   繁体   English

数组中的重复输入无效

[英]Duplicates in an array invalid input

I tried making a simple code for checking in an array for duplicate numbers/numbers that are smaller than the size of the array and numbers that are bigger than the size of the array. 我尝试编写一个简单的代码来检查数组中是否存在重复的数字/小于数组大小的数字和大于数组的数字。 (for example for an array by the size of 7, the number in the array should be between 1-7 with no duplicates, if not the system will print invalid error) when I enter an array by the size of 1 and enter the number 2 for example I get the following error message: (例如,对于大小为7的数组,该数组中的数字应在1-7之间且没有重复,否则,系统将显示无效错误)当我输入大小为1的数组并输入数字时2例如,我收到以下错误消息:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1 at sumn.main(sumn.java:24) 线程“主”中的异常java.lang.ArrayIndexOutOfBoundsException:sumn.main处为1(sumn.java:24)

Here is the code itself, any thoughts on how to fix this? 这是代码本身,对如何解决此问题有何想法?

public class sumn {
    public static boolean Duplicates(int arr[]) {
        int a, b;
        boolean flag = true;
        for (a=0;a<arr.length-1;a++) {
            for (b=a+1;b<arr.length;b++) {
                if (arr[b]==arr[a]) {
                    return false;                       
                }               
            }
        }
        return flag;
    }

    public static void main(String[] args) {
        int N = MyConsole.readInt("Enter the size of the array:");
        int arr[] = new int [N];
        int i, j;
        boolean flag = true;
        for (i=0;i<arr.length;i++) {
            arr[i]= MyConsole.readInt("Enter a number between 1 to ");  
        }
        for (j=0;j<arr.length;j++) {
            if (Duplicates(arr)==false || N<arr[i] || arr[i]<=0) 
                flag = false;
            if (flag == false)  {
                System.out.println("Invalid input");
            }
        }   
    } 


}

Problem is in this line 问题在这条线

if (Duplicates(arr)==false || N<arr[i] || arr[i]<=0) 

make it 做了

if (Duplicates(arr)==false || N<arr[j] || arr[j]<=0) 

replace i with j j代替i

I'm guessing line 24 is if (Duplicates(arr)==false || N<arr[i] || arr[i]<=0) . 我猜第24行是if (Duplicates(arr)==false || N<arr[i] || arr[i]<=0) The problem here is that after your first loop, i will have the value of arr.length . 这里的问题是,在您的第一个循环之后, i将获得arr.length的值。 This will cause an ArrayIndexOutOfBoundsException everytime. 每次都会导致ArrayIndexOutOfBoundsException

You can either replace i with j on that line, which seems to be what you intended to do. 您可以在该行上用j替换i ,这似乎是您想要的。 Or you can "clean up" a bit and scope i to only the loops by writing your loops like: 或者,您可以通过编写类似以下的循环来“清理”一下并将范围i为仅循环:

for(int i = 0; i < arr.length; i++) { ... }

instead of 代替

int i;
for(i = 0; i < arr.length; i++) { ... }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM