我的以下代码有问题。完整的错误如下所示:
java.io.FileNotFoundException: text.txt (The system cannot find the file specified)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(Unknown Source)
at java.io.FileInputStream.<init>(Unknown Source)
at java.util.Scanner.<init>(Unknown Source)
at AAlg.main.main(main.java:42)
这是代码:
package AAlg;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class main {
public static void main(String[] args) {
try {
Scanner s = new Scanner(new File("words.txt"));
ArrayList<String> a =new ArrayList<String>();
while(s.hasNextLine()) {
a.add(s.nextLine());
}
Collections.sort(a);
ArrayList<Node> nodes = new ArrayList<Node>();
for(int i=0;i<a.size();i++) {
nodes.add(new Node(a.get(i)));
}
// System.out.println(a.toString());
BBST b = new BBST();
b.root = b.add(nodes, 0, nodes.size()-1);
long start_time = System.nanoTime();
Scanner s2 = new Scanner(new File("text.txt"));
while(s2.hasNext()) {
String ss = s2.next();
// System.out.println(ss);
b.find(ss.toLowerCase());
}
long end_time = System.nanoTime();
System.out.print((end_time - start_time) / 1e6);
// s2.preorder(s2.root);
// System.out.print(nodes.get(nodes.size()/2).left.value);
// s2.add(a, 0, a.size()-1);
// System.out.println(a.size());
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class BBST{
Node root;
public BBST() {
root=null;
}
public Node add(ArrayList<Node> nodes,int start,int end) {
if(start > end)
return null;
int mid = (start+end)/2;
// System.out.println();
// System.out.println("mid= "+mid+" start= "+start+" end= "+end);
Node node = nodes.get(mid);
node.left = add(nodes,start,mid-1);
node.right = add(nodes,mid+1,end);
return node;
}
boolean find(String value) {
Node tmp = root;
Node pre = null;
while(tmp != null) {
pre=tmp;
boolean large = false;
if(tmp.value.equals(value))
return true;
for(int i=0;i<value.length();i++) {
if(i < tmp.value.length() && i < value.length() && value.charAt(i) != tmp.value.charAt(i)) {
if(value.charAt(i) < tmp.value.charAt(i)) {
large=true;
break;
}
}
}
if(large) {
tmp = tmp.left;
}
else {
tmp = tmp.right;
}
}
return false;
}
}
class Node
{
String value;
Node left, right;
public Node(String value)
{
this.value=value;
left=null;
right=null;
}
}
这是由于txt文件位置出现问题。
如果它与当前类位于同一目录中,请尝试以下操作:
URL path = this.getClass().getResource("words.txt");
Scanner s = new Scanner(new File(path.getFile()));
或者您可以使用从src文件夹开始的路径
Scanner s = new Scanner(new File("src/AAlg/words.txt"));
//put your correct path strting from src, here I took this path from your comment
在运行之前,请确保先清理构建,然后重新构建。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句