如何按字母顺序合并两个字符串?

How to merge two strings alphabetically?

这里是初学者。 我正在尝试使用 compareTo 方法按字母顺序合并到字符串,但是我的 fullfirstarray[i] = arrayone[i];fullsecondarray[i] = arraytwo[i]; 行以及我最后的黑色代码给我错误,主要是 OutofBoundsExceptions

`import java.util.Scanner;
import java.lang.Math; 


class NamesMerge
{
public static void main(String[] args)
 {
  Scanner scan = new Scanner (System.in); 

  int flag = 0;
  int i = 0;
  String name = "";
  String input = "";
  int firstcounter = 0;
  int secondcounter = 0;

  String[] fullfirstarray = new String[firstcounter];
  String[] fullsecondarray = new String[secondcounter];

  System.out.println("Enter the values for the first array, up to 10000 values, enter 'End' to quit");

  //first array prompt (arrayone)
  String[] arrayone = new String[10000];

    input = scan.nextLine();

    input = input.toLowerCase();
    input = input.substring(0, 1).toUpperCase() + input.substring(1);

  while (!(input.equals("End")))
  {
    System.out.println(input);
    arrayone[i] = input;
        i++;
    input = scan.nextLine();
    input = input.toLowerCase();
    input = input.substring(0, 1).toUpperCase() + input.substring(1);
  }

  if (input.equals("End"))
  {
    System.out.println("Enter the values for the second array, up to 10000 values, enter 'End' to quit");
  }

  //next array prompt (arraytwo)
  String[] arraytwo = new String[10000];

    input = scan.nextLine();
    input = input.toLowerCase();
    input = input.substring(0, 1).toUpperCase() + input.substring(1);

  while (!(input.equals("End")))
  {
    System.out.println(input);

    arraytwo[i] = input;
        i++;
    input = scan.nextLine();
    input = input.toLowerCase();
    input = input.substring(0, 1).toUpperCase() + input.substring(1);    
  }

  //PRINTING THE FIRST ARRAY
  if (input.equals("End"))
  {
    System.out.println("First Array");
  }


  for (i =0; i < arrayone.length; i++)
  {
    if  (arrayone[i]!=null)
    {
      System.out.print(arrayone[i] + " ");
             firstcounter++;  
      fullfirstarray[i] = arrayone[i];
    }
  }

  //PRINTING THE SECOND ARRAY
  System.out.println("\nSecond Array");

  for (i =0; i < arraytwo.length; i++)
  {
    if  (arraytwo[i]!=null)
    {
      System.out.print(arraytwo[i] + " ");
              secondcounter++; 
      fullsecondarray[i] = arraytwo[i];
    }
  }


  //counter for total names
  System.out.println(firstcounter);
  System.out.println(secondcounter);


  //merge
  String[] merge = new String[firstcounter + secondcounter];

  int arrayoneindex = 0; 
  int arraytwoindex = 0;

  for (i = 0; i < (firstcounter + secondcounter); i++)
    if (fullfirstarray[i].compareTo(fullsecondarray[i])<0)
    {
    merge[i] = fullfirstarray[i]; 
    arrayoneindex++;
    }
  else
    if (fullsecondarray[i].compareTo(fullfirstarray[i])<0)
    {
      merge[i] = fullsecondarray[i];
      arraytwoindex++;
    }
  for (i = 0; i<merge.length; i++)
    {
      System.out.print(merge[i]);
    }
    }

    }

您的代码smell

正如我所看到的,您需要用字符串填充两个数组,然后将它们按字母顺序组合到新数组中。 试试这个:

    List<String> result = new ArrayList<>();
    result.addAll(Arrays.asList(arrayOne));
    result.addAll(Arrays.asList(arrayTwo));
    result.sort(String.CASE_INSENSITIVE_ORDER);
    String[] resultArray = result.toArray(new String[]{});

此代码的数组版本:

    String[] result = new String[one.length + two.length];
    System.arraycopy(one, 0, result, 0, one.length );
    System.arraycopy(two, 0, result, one.length, two.length);
    Arrays.sort(result, String.CASE_INSENSITIVE_ORDER);

当您尝试访问数组 'fullfirstarray' 时出现异常问题。 当一个数组被声明和实例化时,你是在告诉编译器它将有多少个元素,并且你是在告诉编译器它将有 0:

int firstcounter = 0;
int secondcounter = 0;

String[] fullfirstarray = new String[firstcounter];
String[] fullsecondarray = new String[secondcounter];

因此,当您尝试以这种方式填充数组时:

     fullsecondarray[i] = arraytwo[i];

您尝试访问不存在的数组元素。

当您知道需要的长度时,尝试创建数组。

代码将在下一行失败,但我鼓励您尝试找出问题所在;)

这些行导致了您的 OutOfBoundsException(它们正在创建长度为 0 的数组):

    int firstcounter = 0;
    int secondcounter = 0;

改变这些,异常就会消失

这是您的工作代码。请比较两者并查看差异。这是我所做的高级更改

  1. 重构了代码
  2. 处理边缘情况
  3. 对输入数组进行排序

如果您有任何其他问题,请告诉我。

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

class NamesMerge {

  public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    System.out.println("Enter the values for the first array, up to 10000 values, enter 'End' to quit");
    String[] arrayOne = getArray(scan);
    System.out.println("Enter the values for the second array, up to 10000 values, enter 'End' to quit");
    String[] arrayTwo = getArray(scan);

    sortArray(arrayOne);
    sortArray(arrayTwo);
    //merge
    String[] merge = mergeAndSort(arrayOne, arrayTwo);

  }

  private static String[] mergeAndSort(String[] arrayOne, String[] arrayTwo) {
    String[] merge = new String[arrayOne.length + arrayTwo.length];

    int arrayOneindex = 0;
    int arrayTwoindex = 0;
    int mergeIndex = 0;

    while (arrayOneindex + arrayOneindex < arrayOne.length + arrayTwo.length
        && arrayOneindex < arrayOne.length
        && arrayTwoindex < arrayTwo.length) {

      if (arrayOne[arrayOneindex].compareTo(arrayTwo[arrayTwoindex]) < 0) {
        merge[mergeIndex] = arrayOne[arrayOneindex];
        arrayOneindex++;
        mergeIndex++;
      } else if (arrayOne[arrayOneindex].compareTo(arrayTwo[arrayTwoindex]) >= 0) {
        merge[mergeIndex] = arrayTwo[arrayTwoindex];
        arrayTwoindex++;
        mergeIndex++;
      }
    }

    while (arrayOneindex < arrayOne.length) {
      merge[mergeIndex] = arrayOne[arrayOneindex];
      mergeIndex++;
      arrayOneindex++;
    }
    while (arrayTwoindex < arrayTwo.length) {
      merge[mergeIndex] = arrayTwo[arrayTwoindex];
      mergeIndex++;
      arrayTwoindex++;
    }
    System.out.println("\nMerged sorted array");
    print(merge);
    return merge;
  }

  private static String[] getArray(Scanner scan) {
    String input;
    List<String> list = new ArrayList<>();

    input = scan.nextLine();
    input = input.toLowerCase();
    input = input.substring(0, 1).toUpperCase() + input.substring(1);

    while (!(input.equals("End"))) {
      System.out.println(input);
      list.add(input);
      input = scan.nextLine();
      input = input.toLowerCase();
      input = input.substring(0, 1).toUpperCase() + input.substring(1);
    }
    return list.toArray(new String[list.size()]);
  }

  private static void print(String[] arr) {
    if (arr != null) {
      for (int i = 0; i < arr.length; i++) {
        System.out.print(arr[i] + " ");
      }
    }
  }

  private static String[] sortArray(String[] arr) {
    String temp;
    for (int i = 0; i < arr.length; i++) {
      for (int j = 0; j < arr.length; j++) {
        if (arr[i].compareTo(arr[j]) < 0) {
          temp = arr[i];
          arr[i] = arr[j];
          arr[j] = temp;
        }
      }
    }
    System.out.println("SortedArray");
    print(arr);
    return arr;
  }

}