代码编译,但是当我执行它时,错误显示
“java.util.NoSuchElementException”并突出显示湿度= input.next();
示例输出如下:
K-Nearest Neighbor Prediction Program:
The values you entered are: sunny cool high true
Comparring the values: sunny hot high false dist = 2 and play = no
Comparring the values: sunny hot high true dist = 1 and play = no
Comparring the values: overcast hot high false dist = 3 and play = yes
Comparring the values: rainy mild high false dist = 3 and play = yes
Comparring the values: rainy cool normal false dist = 3 and play = yes
这是我的代码:
import java.util.Scanner;
public class lab2
{
public static void main (String [] args)
{
Scanner input = new Scanner ("data.txt");
System.out.println("The values you entered are : ");
String queryOutlook = "sunny";
String queryHumidity = "high";
String queryTemp = "cool";
String queryVerd = "true";
String outlook = null;
String humidity = null;
String temp = null;
String verd = null;
String play= null;
int distance = 0;
while(input.hasNext())
{
outlook = input.next();
***humidity = input.next();***
temp = input.next();
verd = input.next();
if (!outlook.equalsIgnoreCase(queryOutlook) )
distance++;
if (!humidity.equalsIgnoreCase(queryHumidity) )
distance++;
if (!temp.equalsIgnoreCase(queryTemp) )
distance++;
if (!verd.equalsIgnoreCase(queryVerd) )
distance++;
System.out.println(outlook + humidity + temp + verd + "\t" + play + distance);
这个程序再次与K-nearest邻居预测有关,这是我自上次上课以来从未听说过的。任何帮助,将不胜感激!!!
答案 0 :(得分:4)
while(input.hasNext()) {
outlook = input.next();
humidity = input.next();
temp = input.next();
verd = input.next();
您正在检查输入是否包含下一个元素,如果有,则获得下一个元素。你应该在获得它们之前进行检查。
答案 1 :(得分:3)
Scanner()的构造函数将java.io.File作为输入。你传给它一个字符串。因此,您的扫描仪只扫描字符串“data.txt”以查找匹配项,它实际上从未打开过该文件并对其进行扫描。
你需要做这样的事情,开始:
File f = new File("data.txt");
Scanner input = new Scanner(f);
... // and so on