2014-12-05 40 views
0

我不知道如何讓用戶輸入三個唯一的數字。我試圖創建另一個數組,添加輸入並檢查損壞數組以確保所有數字都是唯一的,但似乎不起作用。感謝您的任何幫助!!只接受來自用戶的唯一輸入到ArrayList

ArrayList<Integer> damage = new ArrayList<Integer>(); 

    ArrayList<Integer> unique = new ArrayList<Integer>(); 
    for (int k = 0; k<=10; k++) 
    { 
     unique.add(k); 
    } 
    do 
    { 
     System.out.print("Attack or Defend? (A or D) "); 
     option = keyboard.nextLine().toUpperCase(); 
     System.out.println(); 
     switch (option) 
     { 
      case "A": 
       System.out.println("Enter three unique random numbers (1-10)"); 
       for(int i = 0; i<3; i++) 
       { 
        System.out.print("number " + (i+1) + ": "); 
        input = keyboard.nextInt(); 
        if (input < 1 || input > 10) 
        { 
         System.out.println("Error! Enter a valid number (1-10)"); 
        } 
        else 
        { 
         if (unique.contains(input)) 
         { 
          unique.remove(input); 
          System.out.println(unique); 
          damage.add(input); 
          System.out.println(damage); 

          i--; 
         }       
         else 
         { 
          unique.add(0, input); 
          System.out.println("Number is not unique!"); 
         } 

        } 
       } 
       System.out.println(damage); 
       System.out.println(); 
       UserDamage ahit = new UserDamage(damage, option); 
       name.getName(); 
       ahit.setUserDamage(damage, option); 
       System.out.println("\n"); 
       cpuHealth-=ahit.getUserDamage(); 
       cpu.setCpuDamage(); 
       userHealth-=cpu.getCpuDamage(); 
       System.out.println("\n\nHealth left: " + userHealth); 
       System.out.println("Computer health left: " + cpuHealth + "\n"); 
       damage.clear(); 
       option = null; 
       break; 


      default: 
       System.out.println("Invalid selection."); 
       break; 
     } 
    } 
    while(userHealth>0 || cpuHealth >0); 

回答

2

java.util.List使用contains方法來確定,如果該項目已經存在。根據JavaDoc:

布爾包含(對象o)

返回true,如果此列表包含 指定的元素。更正式地說,當且僅當此列表包含至少一個元素e以使得(o == null?e == null: o.equals(e))返回true。

0

contains()方法應該對你有用。因此,輸入一個數字可能如下所示:

while(input > 10 || input < 0 || damage.contains(input)) { 
    System.out.print("number " + (i+1) + ": "); 
    input = keyboard.nextInt(); 
} 
0

您已接近。在這裏只需要更多的邏輯工作,並使用Mike Kobit所建議的。

ArrayList<Integer> damage = new ArrayList<Integer>(); 

System.out.println("Enter three unique random numbers (1-10)"); 
      for(int i = 0; i<3; i++) 
      { 
       System.out.print("number " + (i+1) + ": "); 
       input = keyboard.nextInt(); 

       if(damage.contains(input) == false && input > 0 && input <= 10) 
        damage.add(input); 
       else{ 
        System.out.println("Error! Enter an unique valid number (1-10)"); 
        i--; 
       } 
      } 

i--是循環的,所以如果你輸入了3次錯誤的值,沒有值會進入數組。