Ben*_*zle 0 java arrays file quicksort
怎么了,
我试图用Java编写一些代码来读取文件中的数字(每行.txt文件中的一个#)将它们放入一个数组中,然后对数组进行快速排序.Eclipse正在显示一些我遇到问题的红色.我的错误标有评论,错误是什么,如果有人可以帮我运行,谢谢大家!
-Kyle
好的,我更新了前两个答案,谢谢到目前为止,但还有两个错误我真的不理解.
import java.io.*;
import java.util.Scanner;
import java.io.BufferedReader;
import java.io.File;
public class Lab3 {
public static void main(String[] args) throws IOException{
System.out.print("Name of file with array: ");
Scanner readIn = new Scanner(System.in);
String input=readIn.nextLine();}
**testScan1(input);** //Return Type for method is missing (but I am trying to call the method here)
public static void testScan1(String filename)
{
File file = new File(filename);
Scanner scan;
int [] array = new int[5];
try{
scan = new Scanner( file );
}
catch ( java.io.FileNotFoundException e )
{
System.out.println( "couldn't open. file not found " );
return;
}
while(scan.hasNext())
{
for( int i = 0; i <= file.length(); ++i)
{
**array[i]=scan.next();** /*Type mismatch, cannot convert from sting to int. (I moved the declaration about try?)*/
}
int partition(int arr[], int left, int right)
{
int i=left; int j = right;
int tmp;
int pivot = arr[(left+right)/2];
while (i<=j){
while(arr[i]<pivot)
i++;
while (arr[j]>pivot)
j--;
if (i<=j){
tmp=arr[i];
arr[i]=arr[j];
arr[j]=tmp;
i++; j--;
}
}
return i;
}
void quickSort(int arr[], int left, int right){
int index = partition(arr, left, right);
if (left<index-1);
quickSort(arr, left, index-1);
if (index<right)
quickSort(arr, index, right);
}
}
Run Code Online (Sandbox Code Playgroud)
任何时候你处理递归算法并且你得到堆栈溢出,这是因为你的算法没有明确定义的边缘情况会导致你的递归终止.(或者你的输入太大了,但这种情况很少发生,而且情况并非如此.)
你应该看一下你的quickSort()方法,看看是什么让它无限地调用它自己.想想看两个镜子的反射,其中反射从另一个反射反射,然后变成无限......这就是这里发生的事情.
此外,在Java语言中,建议始终使用大写字母开始您的类名.我会说出你的课程QuickSortHomework或类似的东西.
此外,您可能希望了解if语句如何在Java中工作,以及如何定义"块".你有一个if附近一个分号和一对花括号的声明可能没有做你认为它正在做的事情.
老实说,我对这里的所有转发和转发都感到有点恼火.
这不是你想听到的,但我觉得你正在使用这个网站作为拐杖.你似乎没有花时间自己解决正在发生的事情.令人费解的过程,无论多么痛苦,都是真正的学习来源.
在这种情况下,如果您查看该错误的含义,然后您只是查看了您的quickSort()实现,我认为您必须注意到它有一些非常明显的错误.
编辑:如果你正在考虑"但我确实试图解开它"......在你的帖子中包含它确实很有帮助,"我认为这可能是这个,但是这不起作用,所以我想也许它可以是......等等.当你试图像这样说话的时候,你会突然意识到这个问题.另一半,至少我们看到你正在努力.