我正在嘗試制作一個在陣列中獲取并回傳不同值的程式。有趣的是,程式本身可以作業,但是當我嘗試添加一個 do while sentinel 回圈時,程式在第二次嘗試輸入值時崩潰。IDE 沒有回傳錯誤,所以我想看看我的邏輯是否在某個地方出錯了?
import java.util.Scanner;
public class DistinctValuesCourtney {
static int n = 0;
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] distinct;
int i;
int[] array;
array = new int[10];
Scanner input = new Scanner(System.in);
int largestValue;
char doAgain;
do {
System.out.print("Please enter 10 integers for the array:"); //
for (i = 0; i < array.length; i )
{
array[i] = input.nextInt();
}
distinct = getDistinct(array);
System.out.print("You entered these values ");
for (int index = 0; index < n; index ) //use index instead of i
{
System.out.print( distinct[index] " ");
}
System.out.println("Would you like to retry? Y/N: ");
doAgain = input.next().charAt(0);
}
while ((doAgain == 'Y') || (doAgain == 'y'));
System.out.println("Have a nice day!");
}
public static int[] getDistinct(int[] inputArray)
{
int[] finalArray = new int[10];
for (int i = 0; i < inputArray.length; i )
{
int j; //see if this is printed
for (j = 0; j < i; j )
if (inputArray[i]== inputArray[j])
break;
if (i == j)
{
finalArray[n ] = inputArray[i];
//System.out.print( inputArray[i] " ");
}
}
return finalArray;
}
}
uj5u.com熱心網友回復:
您將ArrayIndexOutOfBoundsException在您的getDistinct()方法中得到一個n靜態的,并且在您第二次輸入數字時將大于 9。因此,如果您不需要全域引數,通常應該避免使用它們。全域狀態會導致各種問題。
您可以在方法中的回圈int n = 0;之前添加這一行 (),您的代碼將正常作業。forgetDistinct()
public static int[] getDistinct(int[] inputArray)
{
int[] finalArray = new int[10];
int n = 0; // use a local variable here which will have value 0 everytime you execute the method!
for (int i = 0; i < inputArray.length; i )
{
int j;
for (j = 0; j < i; j )
if (inputArray[i]== inputArray[j])
break;
if (i == j)
{
finalArray[n ] = inputArray[i];
//System.out.print( inputArray[i] " ");
}
}
return finalArray;
}
僅供參考:有更快/更好的方法來消除重復項,例如使用適當的演算法或散列進行排序。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/522535.html
標籤:爪哇循环做时
