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

时间:2017-11-26 22:46:31

标签: java arrays compareto

初学者。 我正在尝试使用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]);
    }
    }

    }

3 个答案:

答案 0 :(得分:0)

您的代码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);

答案 1 :(得分:0)

当您尝试访问阵列时,会出现例外问题&#39; fullfirstarray&#39;。 当声明并实例化一个数组时,你告诉编译器它将拥有多少个元素,并告诉编译器它将具有0:

int firstcounter = 0;
int secondcounter = 0;

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

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

     fullsecondarray[i] = arraytwo[i];

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

尝试在知道所需的长度时创建数组。

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

答案 2 :(得分:0)

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

  1. 重构代码
  2. 处理边缘案例
  3. 对输入数组进行排序
  4. 如果您有任何其他问题,请与我们联系。

    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;
      }
    
    }