預期輸出:用法:java Main 1 2 3 4 5 5 從數字 1 2 3 4 5 5 中洗掉重復項 java Main 1 2 3 4 5 5 這是不同的數字 1 2 3 4 5
輸出:用法:java Main 1 2 3 4 5 5 從數字中洗掉重復項 1 2 3 4 5 5 java Main 1 2 3 4 5 5 執行緒“main”中的例外 java.lang.ArrayIndexOutOfBoundsException:索引 5 超出長度范圍5 在 Main.main(Main.java:26)
/*
Johnny Santamaria
CS 111B Assignment 5 - deDup
This program gives you instructions to remove duplicate numbers in an array
*/
class Main {
public static void main(String[] args) {
int[] numArray;
int index = 0;
int num;
if (args == null || args.length < 1) {
System.out.println("Usage: java Main 1 2 3 4 5 5 to remove duplicates from the numbers 1 2 3 4 5 5");
return; //exit function
}
//finds integers in command line
index = args.length;
numArray = new int[index];
//convert to integers to actually make the array
for (String arg : args) {
num = Integer.parseInt(arg);
numArray[index] = num;
index ;
}
int uniqueIndex = deDup(numArray, index);
}
public static int deDup(int[] numArray, int index) {
if (index == 0 || index == 1) {
return index;
}
//creates new index to store unique numbers
int uniqueIndex = 0;
//checks each number in the array to remove duplicates to make a new index
for (int i = 0; i < index - 1; i ) {
//deletes a number in the index of the array then reformats them
if (numArray[i] != numArray[i 1]) {
numArray[uniqueIndex ] = numArray[i];
}
}
numArray[uniqueIndex ] = numArray[index - 1];
System.out.println("Here are the distinct numbers: " numArray[uniqueIndex]);
return uniqueIndex;
}
}
uj5u.com熱心網友回復:
例外訊息表明您正在嘗試訪問不存在的索引:
執行緒“主”java.lang.ArrayIndexOutOfBoundsException 中的例外:索引 5 超出 Main.main(Main.java:26)處長度 5 的范圍
此行發生非法訪問:
numArray[index] = num;
原因是變數numArray的值沒有索引。index
PS:請注意,在第 19 行,您將 的長度分配給args變數index。
uj5u.com熱心網友回復:
問題是您定義了這些值:
index = args.length;
numArray = new int[index];
然后在您訪問的第一個回圈迭代中
numArray[index] = num;
這不是一個有效的索引,因為它太大了 1。
這里真正的問題是您index在回圈中用作運行變數,但它沒有設定為0. 您將相同的變數用于兩個不同的目的。
任何一個
index = 0;在回圈之前設定或- 在回圈中使用不同的變數,例如
i:
int i = 0;
for (String arg : args) {
num = Integer.parseInt(arg);
numArray[i ] = num;
}
uj5u.com熱心網友回復:
將數字添加到集合是一種簡單的方法
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/426715.html
