2017-11-15 13 views
-2

현재 두 개의 다른 배열에서 문자열 목록을 생성하는 프로그램을 만들고 있지만, 현재는 여러 번 반복하여 원하는 횟수만큼 문자열을 반복적으로 생성합니다.배열을 두 번 이상 복제하지 않고 임의로 문자열을 생성 할 수있는 방법이 있습니까?

public class ListGenerator 
    { 
      public static void main(String[] args) 
      { 
      //number generator to determine which string to print 
      Random generator = new Random(); 
      int rand; 

      //counter to determine number of printed lines 
      int counter = 0; 

      //coin flip to say which array the string will come from 
      Random coinFlip = new Random(); 
      int coin; 

      String[] list1; 
      list1 = new String[5] 
      list1[0] = "Alpha" 
      list1[1] = "Beta" 
      list1[2] = "Charlie" 
      list1[3] = "Delta" 
      list1[4] = "Echo" 

      String[] list2; 
      list2 = new String[5] 
      list2[0] = "Apple" 
      list2[1] = "Pear" 
      list2[2] = "Grape" 
      list2[3] = "Banana" 
      list2[4] = "Orange" 

      for(counter = 0; counter < 15; counter++) 
      { 
       coin = coinFlip.nextInt(2)+1; 

       if(coin == 1) 
       { 
         rand = generator.nextInt(list1.length); 
         System.out.println(list1[rand]); 
       } 
       else if(coin == 2) 
       { 
         rand = generator.nextInt(list2.length); 
         System.out.println(list2[rand]); 
       } 
      } 
      } 
    } 

내가 생성 더 이상 15 개 라인의 두 배 이상 "사과"또는 "베타"와 같은 문자열을 생성 할 수 있도록 만들 수있는 방법이 있습니까?

예 원하는 출력 : 그 문자열의

(1) Apple [printed first time] 
    (2) Charlie [printed first time] 
    (3) Pear [printed first time] 
    (4) Beta [printed first time] 
    (5) Apple [printed second time] 
    (6) Echo [printed first time] 
    (7) Banana [printed first time] 
    (8) Banana [printed second time] 
    (9) Echo [printed second time] 
    (10) Alpha [printed first time] 
    (11) Grape [printed first time] 
    (12) Delta [printed first time] 
    (13) Beta [printed second time] 
    (14) Orange [printed first time] 
    (15) Grape [printed second time] 

5 번이 아닌 두 번 이상 발생하고, 대신 내 코드에 그 문자열 3, 4, 5 등 시간 중 하나를 생성 할 수 .

나는 내 코드가 추가 list1list2 각 값, 최고 또는 그냥

+0

은 BTW, 당신은 당신의 초기화에'리스트 2 [0]'다섯 번 반복합니다. –

답변

0

새로운 ArrayList (20)의 값을 생성이 중복 일에 도움이 필요한 가장 효율적인 조직하지 알고 두번.

이제 shuffle() 목록에서 첫 15 개의 값을 가져옵니다.

String[] list1 = { "Alpha", "Beta", "Charlie", "Delta", "Echo" }; 
String[] list2 = { "Apple", "Pear", "Grape", "Banana", "Orange" }; 

List<String> allTwice = new ArrayList<>(20); 
allTwice.addAll(Arrays.asList(list1)); 
allTwice.addAll(Arrays.asList(list1)); 
allTwice.addAll(Arrays.asList(list2)); 
allTwice.addAll(Arrays.asList(list2)); 
Collections.shuffle(allTwice); 
String[] result = allTwice.subList(0, 15).toArray(new String[15]); 

for (String value : result) 
    System.out.println(value); 

예 출력

Alpha 
Charlie 
Echo 
Apple 
Grape 
Delta 
Apple 
Echo 
Grape 
Banana 
Orange 
Orange 
Pear 
Charlie 
Beta