我正在实现一个驱动程序来测试决策树,并且我得到一个输入不匹配异常。我该怎么做才能解决这个问题?
这是我的代码:
import java.io.FileNotFoundException;
/**
* LoanApprovalAnaylyzer demonstrates the use of a binary decision tree to
* decide the approval of a loan.
*/
public class LoanApprovalAnalyzer
{
/**
* Asks questions of the user to get their credit worthiness.
*/
public static void main (String[] args) throws FileNotFoundException
{
System.out.println ("So, you need a loan.");
DecisionTree expert = new DecisionTree("input2.txt");
expert.evaluate();
}
}
这是我的输入文件:
13
Is your income above $100,000?
Do you have more than 3 dependants?
Do you have more than 6 dependants?
Do you own real estate worth less than $200,000?
Do you own real estate worth more than $200,000?
Are you above the age of 60?
Are you above the age of 45?
Your loan is not approved.
Your loan is approved.
Your loan is not approved.
Your loan is approved
Your loan is not approved.
Your loan is approved
Your loan is not approved.
Your loan is approved
3 7 8
4 9 10
5 11 12
1 3 4
2 5 6
0 1 2
这是我的决策树代码:
import java.util.*;
import java.io.*;
/**
* The DecisionTree class uses the LinkedBinaryTree class to implement
* a binary decision tree. Tree elements are read from a given file and
* then the decision tree can be evaluated based on user input using the
* evaluate method.
*
* @author Java Foundations
* @version 4.0
*/
public class DecisionTree
{
private LinkedBinaryTree<String> tree;
/**
* Builds the decision tree based on the contents of the given file
*
* @param filename the name of the input file
* @throws FileNotFoundException if the input file is not found
*/
public DecisionTree(String filename) throws FileNotFoundException
{
File inputFile = new File(filename);
Scanner scan = new Scanner(inputFile);
int numberNodes = scan.nextInt();
scan.nextLine();
int root = 0, left, right;
List<LinkedBinaryTree<String>> nodes = new java.util.ArrayList<LinkedBinaryTree<String>>();
for (int i = 0; i < numberNodes; i++)
nodes.add(i,new LinkedBinaryTree<String>(scan.nextLine()));
while (scan.hasNext())
{
root = scan.nextInt();
left = scan.nextInt();
right = scan.nextInt();
scan.nextLine();
nodes.set(root, new LinkedBinaryTree<String>((nodes.get(root)).getRootElement(),
nodes.get(left), nodes.get(right)));
}
tree = nodes.get(root);
}
/**
* Follows the decision tree based on user responses.
*/
public void evaluate()
{
LinkedBinaryTree<String> current = tree;
Scanner scan = new Scanner(System.in);
while (current.size() > 1)
{
System.out.println (current.getRootElement());
if (scan.nextLine().equalsIgnoreCase("N"))
current = current.getLeft();
else
current = current.getRight();
}
System.out.println (current.getRootElement());
}
}
答案 0 :(得分:1)
问题在于:
在输入文件中,第一个数字是13,因此您的代码会在下一行(nextInt()
)中跳过13行和EXPECTS以及整数。但是有15行要跳过,这样你就可以在下一行得到一个整数。
解决方案:在输入文件中,在第一行中将13更改为15.