我試圖創建一個代碼來防止重複的數組元素。無論如何,我可以做到這一點,而無需創建一個arrayList?Java - 無論如何,我可以在不使用ArrayList的情況下防止重複數組?
當運行發生該錯誤的程序,當我進入第一#:在線程 「主」 java.lang.ArrayIndexOutOfBoundsException
例外:-1 在DuplicateElimination.main(DuplicateElimination.java:32)
這裏是我的代碼:
int[] numList = new int[5];
int newValue;
boolean invalid;
for (int i = 0; i < numList.length; i++){
do{
System.out.print("Please enter number");
System.out.println(" ");
newValue = input.nextInt();
//This is where the error occurs when I try to compare
//The last list element to the input value
invalid = numList[i-1] == newValue;
if(newValue < 10 || newValue > 100){
System.out.print("Invalid number, Please enter a number between 10 and 100");
newValue = input.nextInt();
}
if(invalid){
System.out.print("That number was entered already try again");
}
}while(invalid);
insertIntoArray(numList, i, newValue);
printArray(numList);
}
開始於:http://stackoverflow.com/questions/5554734/what-causes-a-java-lang-arrayindexoutofboundsexception-and-how-do-i-prevent-it –
可能的重複[我怎麼能測試一個數組是否包含某個值?](http://stackoverflow.com/questions/1128723/how-can-i-test-if-an-array-contains-a-certain-value) – Zircon
你的'for'循環以'i = 0'開始,然後你試圖訪問'numList [i-1]',這有效地是'numList [-1]'。 -1不是一個合適的數組索引,並且錯誤消息很明顯。 –