2013-12-18 34 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的一个更好的性能

相关问题