读取文件并将其排序为Java

时间:2015-10-30 15:24:26

标签: java arrays sorting

我试图写一个能读取文件的程序" data.txt"它以随机顺序具有未定义的数字量,由线分隔。它会将这些数字添加到一个数组中,并在一行中打印出数字,每行用逗号分隔#34; x,x1和#34;。然后在下一行,它将打印出(以相同的格式)从最小到最大尺寸排序的数字列表。

数据类型是整数。

目前,我编写了3种方法,可以对数组进行排序(我认为它们没有错误)。

我已经创建了另一种方法来读取文件并使用两步过程 - 一次计算出文件中的行数(我要求保留这两步过程)。这种方法似乎无法返回" lineCount"显然我需要将这个变量变成一个数组(我觉得这很奇怪)。我该如何修复此代码?

您可能会注意到我的打印方法是空的;我还没有想出一种打印数组的方法,以便每个数字都用逗号分隔。我该如何为此编码?

到目前为止我的代码:

import java.util.*;
import java.io.*;

public class SortAndSearch {
    public static void main(String[] args) {
        readFile2Array();
        printArray();
        selectionSort();
        printArray();
    }

    public static void printArray(int[] a) {

    }

    public static void selectionSort(int[] a) {
        int minI = 0;
        for (int k = 0; k < a.length - 1; ++k) {
            minI = findMinIdx(a, k); // findMinIdx at k-th
            swapElement(a, k, minI);// swapElement at k-th
        }
    }

    public static int findMinIdx(int[] a, int k) {
        int minIdx = k;
        for (int i = k + 1; i < a.length; ++i)
            if (a[i] < a[minIdx])
                minIdx = i;

        return minIdx;
    }

    public static void swapElement(int[] a, int i, int j) {
        int temp;
        temp = a[i];
        a[i] = a[j];
        a[j] = temp;
    }

    public static int[] readFile2Array(String fileName) {

            File dat = new File("data.txt"); 
            int lineCount = 0; 
            int[] a = new int[lineCount];
            int i;

          try{ Scanner sc = new Scanner(dat);

          while (sc.hasNextLine()){ //first read to count -> int lineCount;
          lineCount++; 
          return lineCount; //I have trouble with this line
          }

          while (sc.hasNextLine()){ //second read to array -> hasNext(),
             a[i] = sc.nextInt();

          return a; 
          } 
          } 
          catch (FileNotFoundException e) { 
              System.out.println("File cannot be opened");
              e.printStackTrace();
          } 

    }


      public static int binarySearch(int[] arr, int val){ 
          int minIdx, maxIdx, index = -1; 
          while(){ int middleIdx = (minIdx + maxIdx)/2; 
          if( arr[???] ==val){ 
              index = middleIdx; 
              break } // update minIdx, maxIdx //if smaller then cut right, if larger then cut left 
          }

      return index; }

}

程序中的最后一个方法将尝试使用此(伪)代码找到用户输入数字的元素编号:

1.  Let ‭min = 0‬ and ‭max = n-1‬ (where n is the array’s length)‬‬‬‬
2.  If ‭max < min‬, then stop: ‭target‬ is not present in ‭array‬. return ‭false‬.‬‬‬‬‬‬‬‬
3.  Compute ‭guess‬ as the average of ‭max‬ and ‭min‬, rounded down (so that it is an integer).‬‬‬‬‬‬
4.  If ‭array[guess]‬ equals ‭target‬, then stop. You found it! Return ‭guess‬.‬‬‬‬‬‬
5.  If the guess was too low, that is, ‭array[guess] < target‬, then set ‭min = guess + 1‬.‬‬‬‬
6.  Otherwise, the guess was too high. Set ‭max = guess - 1‬.‬‬
7.  Go back to step 2.

我将如何为此编码?

我非常感谢这个计划的任何领域的任何帮助!

3 个答案:

答案 0 :(得分:0)

我同意VGR你实际上没有问过一个问题,但是通过阅读你的代码,我猜你正在描述你想要实现的目标......

您的readFile2Array方法存在一些缺陷,可能会解决问题:

1)

int lineCount = 0; 
int[] a = new int[lineCount]; //The size of a will always be 0, so you can't add anything to it, even though you are trying to do this later. Consider using a List instead, as the size of the list can increase dynamically.

2)

while (sc.hasNextLine()){ //first read to count -> int lineCount;
    lineCount++; 
    return lineCount; //I have trouble with this line
}
//The problem is the return type: You method signature states that you will return int[], but here you are trying to return an int.
//It will also just increase lineCount once and try to return this. 

3)

//Your scanning will be at the 2nd line because of 2) and not going through the entire file again. To do this you need to create a new instance of Scanner. And the int[] a has a size of 0 at this point. 
while (sc.hasNextLine()){ //second read to array -> hasNext(),
    a[i] = sc.nextInt();
    return a; 
}

因此,为了解决这个问题,您应该将代码重构为:

public static List<Integer> readFile2Array(String fileName) {
    File dat = new File("data.txt"); 
    List<Integer> a = new ArrayList<>();

    try{ Scanner sc = new Scanner(dat);
        while (sc.hasNextLine()){ 
            a.add(sc.nextInt());
        } 

        sc.close(); //Always remember to close, when done :) 
        System.out.println("Added " + a.size() + " lines to the list.");
        return a; 

    } catch (FileNotFoundException e) { 
        System.out.println("File cannot be opened");
        e.printStackTrace();

        return new ArrayList<>();
    } 
}

我改变了什么:

  • 删除了lineCount,因为它隐式存储在名为。
  • 的列表大小中
  • 将int [] a更改为List,因为这总是允许在需要时通过增加元素来添加元素。
  • 删除了i,因为从未使用过,只是初始化。
  • 删除了第一个while循环,因为我们不需要知道要添加的行数。
  • 在catch-closure中添加了一个return语句。我们需要返回一些东西(甚至是一个空数组或者可能还没有完成的数组)

我希望这会有所帮助。 :)

答案 1 :(得分:0)

管理以修复代码的第一部分:

readFile2Array方法:

 public static int[] readFile2Array(String fileName) {
        try {
            int lineCount = 0;

            Scanner sc = new Scanner(new File("data.txt"));
            while (sc.hasNext()) { // first read to count -> int lineCount;
                lineCount++; // second read to array -> hasNext(),
                sc.nextLine();
            }
            sc.close();

            sc = new Scanner(new File("data.txt"));
            int[] x = new int[lineCount];
            int n = 0;
            while (sc.hasNext()) {
                x[n] = Integer.parseInt(sc.nextLine());
                n++;
            }
            sc.close();
            return x;

        } catch (FileNotFoundException e) {
            System.out.println("File cannot be opened");
            e.printStackTrace();
        }
        return null;
    }

以逗号分隔的打印数组:

public static void printArray(int[] a) {
        try {
            int lineCount = 0;

            Scanner sc = new Scanner(new File("data.txt"));
            while (sc.hasNext()) {
                lineCount++;
                sc.nextLine();
            }
            sc.close();

        for (int i = 0; i < a.length; ++i) {
            System.out.print(a[i]);
            if (i < lineCount-1) System.out.print(", ");
        }
        } catch (FileNotFoundException e) {
            System.out.println("File cannot be opened");
        }
        System.out.println();
    }

最后一种方法对我来说仍然是一个谜!

答案 2 :(得分:0)

I'm glad you got that part working. :)

To print out the array, it will be best to use whatever data you have of the array. By calling a.length, you don't have to count the number of lines from the input again, which you are not guaranteed are still the same if the input has changed in the mean time.

So this piece of code should do the trick:

public static void printArray(int[] a) {
    for (int i = 0; i < a.length; ++i) {
        System.out.print(a[i]);
        if (i < a.length-1) System.out.print(", ");
    }

    System.out.println();
}