2013-12-18 35 views
4

我有這個代碼要求用戶輸入數組大小(不能超過50),並且數組大小已成功設置爲數組。告訴用戶輸入的號碼是否已經存儲在陣列中

我的問題是在第二段代碼。 基本上,我希望它存儲由用戶輸入的數字(哪些工作),但是,如果數字已經給予數組,則告知用戶該數字已經被添加並且數字不被存儲。例如:用戶輸入1,4,6,1。當再次給出1時,程序應該告訴用戶數字1已經存儲在數組中。

我能做些什麼,以使程序(使用的ArrayList我可以使用。載,但陣列不具備這一點,似乎)

public static void main(String[] args) { 

    Scanner reader = new Scanner (System.in); 

    int[] listA; 

    while (true) { 

     System.out.println("Enter array size for listA: "); 
     int listAsize = Integer.parseInt(reader.nextLine()); 

     if (listAsize > 50) { 

      System.out.println("Array size must not exceed 50!"); 

     } else { 

      listA = new int [listAsize]; 
      //System.out.println(listA.length); 
      break; 
     } 

    } 


    int counter = 0; 

    while (counter < listA.length) { 

     System.out.print("Enter number to add to listA: "); 
     int inputListA = Integer.parseInt(reader.nextLine()); 

     **if (listA.equals(listA[counter])) {** 

      System.out.println(inputListA + " was already added to the array, enter a different number"); 

     } else { 


      listA[counter] = inputListA; 
      counter++; 

     } 
    } 
+0

保持一個ArrayList的,而不是數組? – smk

回答

2

這種情況是不正確的:

listA.equals(listA[counter]) 

你需要建立一個循環,去從零到counter-1,包容性,並檢查每個對inputListA價值元素。如果值是存在的,循環應該設定一個boolean標誌,就像這樣:

boolean dup = false; 
for (int i = 0 ; i != counter ; i++) { 
    if (listA[i] == inputListA) { 
     dup = true; 
     break; 
    } 
} 
// If we went through listA up to count and dup remained false, 
// listA must be a new number; otherwise, it's a duplicate. 
if (dup) { 
    System.out.println(inputListA + " was already added to the array, enter a different number"); 
} 
+0

非常感謝,這工作! 正是我想要的,也感謝你的其他人爲你提供的幫助 我學到了很多東西,只是讀了所有人人給出的代碼 – user3116280

2

問題在你的代碼:

if (listA.equals(listA[counter])) 

這是將是trueint listA[]

使用而不是

  • 無需指定初始大小
  • add()將返回false如果元素已經存在
1

如果必須使用數組,而不是從引進數組列表限制,你很可能使用Arrays.asList將其轉換爲一個數組名單。

Arrays.asList(yourArr).contains(someVal) 

或者你也可以寫自己的contains方法循環遍歷每個元素,看它是否在數組中的與否。

boolean hasElmt = false; 
for (int val : yourArr) { 
    if (val == someVal) { 
     hasElmt = true; 
     break; 
    } 
} 
1

因爲它是一個原始數組,所以沒有可以使用的方法。您必須使用for循環遍歷數組,並檢查每個索引的值。

for(int i = 0; i < listA.lenght; i++) { 
    if(inputListA == listA[i]) { 
     // it's already on the array 
    } 
} 
2

,如果你需要使用它陣列

int counter = 0; 
while (counter < listA.length) { 
    System.out.print("Enter number to add to listA: "); 
    int inputListA = Integer.parseInt(reader.nextLine()); 
    if (found(listA,inputListA,counter)) { 
     System.out.println(inputListA + " was already added to the array, enter a different number"); 
    } else { 
     listA[counter] = inputListA; 
     counter++; 
    } 
} 

public boolean found (int[]list,int num,int counter){ 
    for(int i = 0;i<counter;i++){ 
     if(list[i]==num) 
     return true; 
    } 
    return false; 
} 

或者您可以使用HashSet的一個更好的性能

相關問題