按特定顺序将两个textarea合并为一个

j5fpnvbx  于 2021-08-25  发布在  Java
关注(0)|答案(2)|浏览(510)

我使用这些数组从textarea获取文本

  1. array1 = textArea1.getText().split("\\r?\\n");
  2. array2 = textArea2.getText().split("\\r?\\n");

我想以一种特定的方式将两者结合起来,并以一个简单的方式展示结果 textArea3 . 例如,我想从 array1 然后是来自 array2 接下来的六个元素来自 array1 所以有一个。。。我如何实现这一点?

ztigrdn8

ztigrdn81#

您想创建一个双for循环。第二个for循环将在第一个for循环每次迭代时通过6个元素。第一个for循环将使用array1,并将其长度除以6,以确定它应该迭代多少次(如果阵列1的长度为12,则循环应循环2次)。第二个循环中还有一个检查,检查i是否为偶数,因此它创建了一个交替模式:
编辑:您希望长度较大的数组成为第一个for循环中使用的数组,以确保所有元素都在两个数组中使用,我使用math.max()方法包括了这两个数组

  1. String result = “”;
  2. for(int i = 0; i < Math.ceil(Math.max(array1.length, array2.length)/6) ; i++) {
  3. for(int j = i*6; j < i*6 + 6; j++) {
  4. if(i % 2 == 0 && j < array1.length) //every time i is even (to ensure alternating pattern
  5. result += array1[j];
  6. else if(j < array2.length)
  7. result += array2[j]; //making sure j is within length of array2
  8. else
  9. break; //j is out of bounds of both arrays, so break the loop
  10. }
  11. }
  12. textArea3.setText(result);

如果有错误,请检查这个循环

展开查看全部
mxg2im7a

mxg2im7a2#

通过将数组转换为某种形式的 Collection 首先要使用它们的功能。这里有一种可能的方法,将它们转换为 ArrayList 首先,然后从ArrayList中删除要追加的值。

  1. import java.util.ArrayList;
  2. import java.util.Arrays;
  3. import java.util.List;
  4. public class GroupArraysTest {
  5. public static void main(String[] args) {
  6. String[] array1 = {"A", "bunch", "of", "values", "for", "testing", "purposes."};
  7. String[] array2 = {"Even", "more", "values", "with", "more", "values", "than", "previous", "array", "for", "testing", "purposes."};
  8. System.out.println(groupArrays(3, array1, array2));
  9. }
  10. public static String groupArrays(int wordCount, String[] array1, String[] array2) {
  11. StringBuilder builder = new StringBuilder();
  12. List<String> list1 = new ArrayList<>(Arrays.asList(array1));
  13. List<String> list2 = new ArrayList<>(Arrays.asList(array2));
  14. while(!list1.isEmpty() || !list2.isEmpty()) {
  15. for(int i = 0; i < wordCount; i++) {
  16. if(!list1.isEmpty())
  17. builder.append(list1.remove(0)).append(" ");
  18. else
  19. break;
  20. }
  21. for(int i = 0; i < wordCount; i++) {
  22. if(!list2.isEmpty())
  23. builder.append(list2.remove(0)).append(" ");
  24. else
  25. break;
  26. }
  27. }
  28. return builder.toString();
  29. }
  30. }
展开查看全部

相关问题