Java 如何从文件中读取字符串并插入到二叉树中
我正在尝试制作一个程序,该程序使用文本文件中的字符串创建用户配置文件,并将每个配置文件插入到二叉树中。一切看起来都应该正常,但在尝试读取文件时,它抛出了一个NoSuchElementFound异常 这是我的文件读取器类:Java 如何从文件中读取字符串并插入到二叉树中,java,binary-tree,filereader,nosuchelementexception,Java,Binary Tree,Filereader,Nosuchelementexception,我正在尝试制作一个程序,该程序使用文本文件中的字符串创建用户配置文件,并将每个配置文件插入到二叉树中。一切看起来都应该正常,但在尝试读取文件时,它抛出了一个NoSuchElementFound异常 这是我的文件读取器类: public class FileReader { public static BST readProfiles(String filename, BST tree){ File inputFile = new File(filename); File
public class FileReader {
public static BST readProfiles(String filename, BST tree){
File inputFile = new File(filename);
FileReader.readFileDate(inputFile, tree);
return tree;
}
public static void readFileDate(File inputFile, BST tree){
Scanner in = null;
try
{
in = new Scanner(inputFile);
}
catch (FileNotFoundException e)
{
System.out.println("Cannot open file");
System.exit(0);
}
FileReader.readLine(in, tree);
}
public static void readLine(Scanner in, BST tree)
{
while (in.hasNextLine())
{
String line = in.nextLine();
if(line.isEmpty()){
continue;
}
Scanner lineScanner = new Scanner(line);
lineScanner.useDelimiter(",|;");
FileReader.createProfile(lineScanner, tree);
}
}
public static Profile createProfile(Scanner lineScanner, BST tree)
{
String name = lineScanner.nextLine();
int dd = lineScanner.nextInt();
int mm = lineScanner.nextInt();
int yyyy = lineScanner.nextInt();
String town = lineScanner.nextLine();
String country = lineScanner.nextLine();
String nationality = lineScanner.nextLine();
String interests = lineScanner.nextLine();
Profile p = new Profile(name, dd, mm, yyyy, town, country,
nationality, interests);
tree.insertProfile(p);
return p;
}
}
下面是我的二叉树类:
public class BST {
private static BSTNode root;
BST(){
}
public void insertProfile(Profile p){
BSTNode currentNode = new BSTNode(p);
if(root == null){
root = currentNode;
}
else{
recursiveMethod(currentNode);
}
}
private static void recursiveMethod(BSTNode currentNode){
Profile p1 = root.getProfile();
Profile p2 = currentNode.getProfile();
if(p1.getName().compareTo(p2.getName()) < 0 && currentNode.getLeft() != null){
recursiveMethod(currentNode.getLeft());
}
if(p1.getName().compareTo(p2.getName()) > 0 && currentNode.getLeft() !=null){
recursiveMethod(currentNode.getRight());
}
}
}
有没有关于如何纠正这种情况的建议?
谢谢我应该把这个放在程序的什么地方?
public class BSTNode {
private BSTNode left;
private BSTNode right;
private Profile data;
public BSTNode(Profile data){
this.data = data;
setLeft(left);
setRight(right);
}
public Profile getProfile(){
return data;
}
public void setLeft(BSTNode l){
this.left = l;
}
public BSTNode getLeft(){
return left;
}
public void setRight(BSTNode r){
this.right = r;
}
public BSTNode getRight(){
return right;
}
String splitProfile[] = lineScanner.split(",");
String fullName = splitProfile[0];