簡體   English   中英

我的while循環中JAVA程序出現運行時錯誤

[英]I have a run time error in my JAVA program in my while loop

代碼可以編譯,但是當我執行它時,錯誤提示

“ 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值最近鄰預測有關,這是自上一堂課以來我從未聽說過的。 任何幫助,將不勝感激!!!

    while(input.hasNext()) {
        outlook = input.next();
        humidity = input.next();
        temp = input.next();
        verd = input.next();

您正在檢查輸入中是否有一個下一個元素,如果有,則得到四個下一個元素。 在獲取每一個之前,您應該檢查一下。

Scanner()的構造函數將java.io.File作為輸入。 您正在傳遞一個字符串。 因此,您的掃描器僅掃描字符串“ data.txt”尋找匹配項,而實際上並沒有打開該文件並對其進行掃描。

您需要執行以下操作來開始:

File f = new File("data.txt");
Scanner input = new Scanner(f);
... // and so on

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM