【问题标题】:Read and Sort a file to array Java读取文件并将文件排序为数组 Java
【发布时间】:2015-10-30 15:24:26
【问题描述】:

我正在尝试编写一个程序来读取文件“data.txt”,该文件具有未定义数量的随机数字,以行分隔。它将这些数字添加到一个数组中并在一行中打印出这些数字,每个数字用逗号“x,x1”分隔。然后在下一行,它将打印出(以相同格式)从最小到最大大小排序的数字列表。

数据类型是整数。

目前,我已经编写了 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.

我将如何编码?

我非常感谢在该计划的任何领域提供任何帮助!

【问题讨论】:

  • 您已经描述了您的程序,但您没有提出任何实际问题。
  • 谢谢,我在遇到问题的三个部分中添加了三个问题。

标签: java arrays sorting


【解决方案1】:

设法修复了代码的第一部分:

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】:

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

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

    【讨论】:

      【解决方案3】:

      我很高兴你让这部分工作。 :)

      要打印出数组,最好使用数组中的任何数据。通过调用 a.length,您不必再次计算输入的行数,如果输入同时发生变化,您不能保证这些行数仍然相同。

      所以这段代码应该可以解决问题:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-11-19
        • 1970-01-01
        相关资源
        最近更新 更多