简体   繁体   English

NoSuchElementException不断被触发,我不确定为什么

[英]NoSuchElementException keeps getting triggered and I'm not sure why

Basically what the aim of my program is, is to select a random quote from a text file and print it based on a random number generated that is no bigger than the number of lines in the file. 基本上,我的程序的目标是从文本文件中选择一个随机引号,然后根据生成的随机数打印该引号,该随机数不大于文件中的行数。 I know the file is in the correct directory and contains all of the content. 我知道该文件位于正确的目录中,并且包含所有内容。

I've tried using both while and for loops, but those seem to be the problem the code runs without error when the loops are not in there, but without the loops, the program doesn't do what I want it to do. 我已经尝试过同时使用while和for循环,但是这似乎是一个问题,当循环不在其中时,代码会正确运行,但是如果没有循环,程序就不会执行我想做的事情。 Also, have tried changing the scope of certain variables. 另外,尝试更改某些变量的范围。

// open file
private static void openFile(){

    try {
        input = new Scanner(Paths.get("Quotes.txt"));
    }
    catch(IOException ioException){
        System.err.println("Error opening file. Terminating.");
        System.exit(1);
    }
}

// get and print quote
private static void printQuote(){

    try {
        int printQue = randomNumber();

        System.out.println(printQue);
        for (int i = 0; i < printQue - 1; i++){
            input.nextLine();
        }

        System.out.printf("The randomly selected quote is: %s%n", 
        input.nextLine());
    }
    catch(NoSuchElementException elementException){
        System.err.println("File formed improperly. Terminating.");
    }
    catch(IllegalStateException stateException){
        System.err.println("Error reading from file. Terminating.");
    }
}

// size of list
private static int fileSize(){

    try{
        int counter = 0;
        while (input.hasNext()){
            input.nextLine();
            counter++;
        }

        num = counter;
    }
    catch(NoSuchElementException elementException){
        System.err.println("File improperly formed. Terminating");
    }
    catch(IllegalStateException stateException){
        System.err.println("Error reading from file. Terminating.");
    }

    return num;
}

// get random number
private static int randomNumber(){

    int randomNum = random.nextInt(fileSize());

    while (randomNum <= 0){
        randomNum = random.nextInt(fileSize());
    }

    return randomNum;
}

Print one of the 100 quotes in the text file. 在文本文件中打印100个引号之一。

Your scanner is iterating over the entire file in your fileSize() method because you're calling input.nextLine() every iteration. 扫描程序会遍历fileSize()方法中的整个文件,因为您每次迭代都会调用input.nextLine()

Once you get to printQuote() you have already iterated over the entire file, so you're trying to read in a line at (last_index + 1). 一旦使用printQuote() ,就已经遍历了整个文件,因此您尝试在(last_index + 1)处读入一行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM