【发布时间】:2018-01-24 01:39:15
【问题描述】:
我的任务是在 java 中执行合并排序功能。我已经弄清楚了合并排序功能。我对这个分配的问题是转换文本文件的每一行整数并对它们中的每一个执行合并排序功能。例如: 3 4 25 5 29 6 12 64 23 11 32 94 12 42 23 55
第一行是文件中包含的数组的数量,接下来的 3 行是我需要执行归并排序的数组。所以我需要对 4 25 5 29 6、12 64 23 11 32 和 94 12 42 23 55 等数组进行归并排序。
我试图做的是创建四个单独的字符串数组来存储每一行整数,所以我使用了扫描仪的 nextLine() 方法。我现在正在处理的问题是弄清楚如何将它们转换为 int 数组而不处理数字格式异常。
这是我的合并排序函数类
public class MergeSort
{
private int[] array;
private int[] tempMergArr;
private int length;
public void sort(int inputArr[])
{
this.array = inputArr;
this.length = inputArr.length;
this.tempMergArr = new int[length];
doMergeSort(0, length - 1);
}
public void doMergeSort(int lowerIndex, int higherIndex)
{
if (lowerIndex < higherIndex)
{
int middle = lowerIndex + (higherIndex - lowerIndex) / 2;
// Below step sorts the left side of the array
doMergeSort(lowerIndex, middle);
// Below step sorts the right side of the array
doMergeSort(middle + 1, higherIndex);
// Now merge both sides
mergeParts(lowerIndex, middle, higherIndex);
}
}
public void mergeParts(int lowerIndex, int middle, int higherIndex)
{
for (int i = lowerIndex; i <= higherIndex; i++) {
tempMergArr[i] = array[i];
}
int i = lowerIndex;
int j = middle + 1;
int k = lowerIndex;
while (i <= middle && j <= higherIndex) {
if (tempMergArr[i] <= tempMergArr[j]) {
array[k] = tempMergArr[i];
i++;
} else {
array[k] = tempMergArr[j];
j++;
}
k++;
}
while (i <= middle) {
array[k] = tempMergArr[i];
k++;
i++;
}
}
}
这是Merge Sort的驱动类,这就是问题所在。
import java.io.*;
import java.util.Scanner;
public class MergeSortDriver
{
public static void main(String args[]) throws IOException
{
String[] array = new String[6];
String[] array1 = new String[6];
String[] array2 = new String[6];
String[] array3 = new String[6];
int i = 0;
File file = new File("input.txt");
Scanner fileReader = new Scanner(file);
array[i] = fileReader.nextLine();
array1[i] = fileReader.nextLine();
array2[i] = fileReader.nextLine();
array3[i] = fileReader.nextLine();
System.out.println(array1[i]);
System.out.println(array2[i]);
System.out.println(array3[i]);
fileReader.close();
MergeSortDriver driver = new MergeSortDriver();
for(int j = 0; j<array1.length; j++)
{
System.out.print(driver.convertToInt(array1)[i]+" ");
}
/*
int[] inputArr = {4,25,5,29,6}; // if I do like this, then the code will work, so the string arrays need to be like this in order to work.
MergeSort mms = new MergeSort();
mms.sort(inputArr);
for(int i:inputArr)
{
System.out.print(i);
System.out.print(" ");
}
*/
}
public static int[] convertToInt(String[] array)
{
int[] ints = new int[array.length];
for(int i = 0; i<array.length; i++)
{
ints[i] = Integer.parseInt(array[i]);
}
return ints;
}
}
希望大家能找出我的驱动类源码中的错误,如果你现在尝试运行程序,你会得到数字格式异常。所以我的目标是将文件中的字符串数组转换为 int 数组而不产生异常。
【问题讨论】:
-
现在是学习如何使用调试器的好时机。