簡體   English   中英

Java循環混亂

[英]Java Loop Confusion

我編寫了這段旨在讀取具有整數值的文件的代碼。 如果整數值> = 0和<= 100,我需要給出等級的平均值。 如果有任何值超出指定范圍0-100,那么我需要計算不正確的整數等級,將不正確的等級告知用戶,並告知有多少不正確的等級。 我嘗試了該代碼,但始終收到錯誤代碼:

Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at Project9.main(Project9.java:26)

代碼示例:

public static void main(String[] args) throws IOException{
    String file;
    int readInts;

    Scanner k = new Scanner(System.in);

    System.out.println("Enter filename: ");
    file = k.nextLine();
    int counterWrong = 0;
    int counterRight = 0;
    int sum = 0;
    double average = 1.0 * sum/counterRight;

    File fileReader = new File(file);

    if (fileReader.exists()) {
        Scanner input = new Scanner(fileReader);
        while (input.hasNext()) {
            readInts = input.nextInt();
            System.out.println(readInts);
            String a = input.next();
            int a2 = Integer.parseInt(a);

        if (a2 <= 100 && a2 >= 0){
            counterRight++;            
            sum = sum + a2; 
            System.out.println("Score " + a2 + " was counted.");

        } else {
            counterWrong++;
            System.out.println("The test grade " + a2 + " was not scored as it was out of the range of valid scores.");
            System.out.println("There were " + counterWrong + " invalid scores that were not counted.");
        }
        }
        if (counterRight > 0){
            System.out.println("The average of the correct grades on file is " + average + ".");
        }
    } else {
        System.out.println("The file " + file + " does not exist. The program will now close.");
    }


}

}

您正在執行一次hasNext檢查,但是隨后使用nextInt()next()從掃描儀讀取了兩次。

使用hasNextInt()代替hasNext()。

hasNext()僅表示存在另一個令牌,並不一定意味着您在編寫nextInt()時假設存在另一個整數。

這是hasNext()hasNextInt()的文檔

您還想在此行之前進行檢查:

String a = input.next();

我看到的代碼可能存在兩個問題。

  1. 文件= k.nextLine(); //根據文件的設置方式,k.nextLine()或k.next()或k.nextInt()可能有用。

  2. while(input.hasNext()){readInts = input.nextInt(); // input.hasNext()假定掃描儀正在讀取的下一個值具有字符串值,該字符串值將使readInts = input.nextInt(); 未經解析(或其他方法)無法使用。

我認為嘗試此練習會很有趣(不想為您毀了它)。 查看我的代碼,希望您能學到我正在談論的一些概念。

注意:我的程序讀取整數值,例如95 185 23 13 90 93 37 125 172 99 54 148 53 36 181 127 85 122 195 45 79 14 19 88 34 73 92 97 200 167 126 48 10938。使用hasNext()和next ()獲取列出的所有令牌。 因此,對於給定的輸入,使用nextLine()不會有用。

封裝cs1410;

import java.io.File;
import java.io.IOException;
import java.util.Scanner;

import javax.swing.JFileChooser;

public class Grader {

    public static void main(String[] args) throws IOException {
        int count = 0;
        int sum = 0;
        double ave = 0;
        int incorrectCount = 0;
        String correctGrades = "";
        String incorrectGrades = "";

        // Read file input
        JFileChooser chooser = new JFileChooser();
        if (JFileChooser.APPROVE_OPTION != chooser.showOpenDialog(null)) {
            return;
        }
        File file = chooser.getSelectedFile();

        // Scan chosen document
        Scanner s = new Scanner(file);


        // While the document has an Int
        while (s.hasNextInt()) {
            // Convert our inputs into an int
            int grade = Integer.parseInt(s.next());

            if (grade >= 0 && grade <= 100) {
                // adds sum
                sum += grade;
                // increments correct count
                count++;
                // displays valid grades
                correctGrades += Integer.toString(grade) + "\n";
            } else {
                // increments incorrect count
                incorrectCount++;
                // displays invalid grades
                incorrectGrades += Integer.toString(grade) + "\n";
            }
        }
        // Created average variable 
        ave = sum / count;

        // bada bing bada boom
        System.out.println("The number of correct grades were " + correctGrades);
        System.out.println("The average score on this test was " + ave + "\n");
        System.out.println("The number of incorrect grades were " + incorrectCount + "\n");
        System.out.println("The incorrect values for the grades were " + "\n" + incorrectGrades);

    }

}

暫無
暫無

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

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