2015-04-19 27 views
0

。每次我打印更新的列表時,它都會給我列出減去隨機選擇的元素並減去另一個元素的數組列表。打印從一個數組列表隨機移除的元素,然後打印出所以我具有由一個ArrayList打印出隨機選擇的元件的問題,然後打印更新的數組列表而不認爲隨機元素更新的數組列表

import java.util.ArrayList; 
import java.util.Scanner; 
import java.util.Random; 

public class LabPartyGuests { 
    public static void main(String[] args) { 
     int numberOfGuests = 4; 
     Scanner input = new Scanner(System.in); 
     Random rand = new Random(); 
     ArrayList<String> guestList = new ArrayList<String>(); 

     System.out.println("Please enter 4 guests: "); 
     System.out.print("guest1: "); 
     String guest1 = input.nextLine(); 
     System.out.print("guest2: "); 
     String guest2 = input.nextLine(); 
     System.out.print("guest3: "); 
     String guest3 = input.nextLine(); 
     System.out.print("guest4: "); 
     String guest4 = input.nextLine(); 

     for (int i = 0; i <= 0; i++) { 
     guestList.add(guest1); 
     guestList.add(guest2); 
     guestList.add(guest3); 
     guestList.add(guest4); 
     } 
     System.out.println(); 
     System.out.print("Guest list: " + guestList); 
     System.out.println(); 

     guestList.remove(rand.nextInt(4)); 
     System.out.printf("%s can't come %n", guestList.remove(rand.nextInt(4))); 
     for (int i = 0; i < guestList.size(); i++) { 
     guestList.size(); 
     } 
     System.out.print(guestList); 
    } 
} 
+0

多少你有幾次在列表中調用remove()?一次或兩次?那你爲什麼感到驚訝? –

回答

1

您卸下兩個要素:

guestList.remove(rand.nextInt(4)); // one 
    System.out.printf("%s can't come %n", guestList.remove(rand.nextInt(4))); // two 

如果你想打印刪除的元素,存儲第一刪除的輸出,而不是調用remove兩次:

String removed = guestList.remove(rand.nextInt(4)); 
    System.out.println("removed element " + removed); 
+0

如何獲取它以打印刪除的元素?如果我只是把rand.nextInt(4)放在那裏,它就會打印出索引。 – james13

+0

@ james13'除去(INT指數)'返回被刪除的元素。只要寫'字符串刪除= guestList.remove(rand.nextInt(4));' – Eran

+0

感謝我想通了沒有使用,但感謝的小費! :) – james13