【发布时间】: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.
我将如何编码?
我非常感谢在该计划的任何领域提供任何帮助!
【问题讨论】:
-
您已经描述了您的程序,但您没有提出任何实际问题。
-
谢谢,我在遇到问题的三个部分中添加了三个问题。