简体   繁体   English

遇到异常,我不知道为什么

[英]Getting exception and I don't know why

import java.util.Scanner;               //Import necessary classes 
import java.text.DecimalFormat;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.FileWriter;
import java.io.FileNotFoundException;



public class Lab11
{
    public static void main (String[] args)
    {
        Scanner scan = new Scanner(System.in);
        DecimalFormat fmt = new DecimalFormat("0.00");

        final int LIMIT = 1000, MAX = 10, MIN = -10;        //number of ints to be read into file
        String fileName;            //holds name of file


        System.out.print("Enter the name of the file to hold the integers: ");
        fileName = scan.next();
        PrintWriter outFile = null;         //creates PrintWriter to write to specified file

        try
        {
            outFile = new PrintWriter(new File(fileName));      //TryCatch statement to catch any errors when file opens
        }
        catch (FileNotFoundException e)
        {
            System.out.println("File "+fileName+" doesn't exist.  Exiting program");
            System.exit(-1);
        }

        for (int i = 0; i <= LIMIT; i++) {        //for loop to write to file using random num between -10 and 10
            outFile.print((int)(Math.random()*(MAX+1-MIN)) + MIN + " ");        //makes sure numbers in file are separated by spaces
            outFile.close();        //closes file for output
        }


        Scanner inFile = null;      //creates scanner to read in file
        try     //TryCatch statement to catch errors
        {
            inFile = new Scanner(new File(fileName));       
        }
        catch (FileNotFoundException e)
        {
            System.out.println("File "+fileName+" doesn't exist.  Exiting program");
            System.exit(-1);
        }

        int num, neg = 0, pos = 0, zero = 0;        //variables to hold current number, positives, negatives and average
        double avg = 0;

        while (inFile.hasNext())        // Use a while loop to read in numbers from the file until the end
        {       
            inFile.nextLine();
            fileName = inFile.nextLine();
            avg = 0;
            num = 0;

            while(inFile.hasNextInt())
            {
                num = inFile.nextInt();
                avg += num;         //adds current num to avg

                if (num > 0)
                    pos++;      //checks if positive and adds one to total pos
                if (num < 0)
                    neg++;      //checks is negative and adds one to total neg
                else
                    zero++;     //checks for zeros and adds one to total
            }
            avg = (avg/LIMIT);      //calculates actual average
            inFile.close();     //closes file for input
        }

        outFile = null;         //Opens file for output again

        try
        {
            outFile = new PrintWriter(new FileWriter(fileName, true));      //TryCatch statement to catch any errors when file opens
        }                                                                       //Allows file to be appended to instead of truncated
        catch (IOException e)       
        {
            System.out.println("File "+fileName+" doesn't exist.  Exiting program");
            System.exit(-1);
        }

            System.out.println("\n\nNumber of negative numbers in the file: " + neg);
            System.out.println("\nNumber of positive numbers in the file: " + pos);
            System.out.println("\nNumber of zeroes in the file: " + zero);
            System.out.println("\nAverage of the numbers in the file: " + fmt.format(avg));

            outFile.print("Number of negative numbers in the file: " + neg);
            outFile.print("Number of positive numbers in the file: " + pos);
            outFile.print("Number of zeroes in the file: " + zero);
            outFile.print("Average of the numbers in the file: " + fmt.format(avg));

            outFile.close();
}  // End of main
}

I'm taking intro to Java and I am just brutal at it. 我正在介绍Java,但我对此很残酷。 No matter how many hours I practice or study I just don't get it. 无论我练习或学习多少小时,我都无法理解。 I got this much done but now I'm getting this. 我已经完成了很多工作,但是现在我已经完成了。

Exception in thread "main" java.util.NoSuchElementException: No line found
  at java.util.Scanner.nextLine(Scanner.java:1585)
  at Lab11.main(Lab11.java:89)

I have no idea where I went wrong. 我不知道哪里出了问题。 Any guidance would be great. 任何指导都会很棒。 Thanks. 谢谢。

Focus on : Exception in thread "main" java.util.NoSuchElementException: No line found 专注于: Exception in thread "main" java.util.NoSuchElementException: No line found

Look at this piece of code. 看一下这段代码。

 while (inFile.hasNext())        // Use a while loop to read in numbers from the file until the end
    {       
        inFile.nextLine();
        fileName = inFile.nextLine();

Say your file has only one line. 假设您的文件只有一行。 Then, inFile.nextLine(); 然后, inFile.nextLine(); has already read it. 已经读过了。 After which there NO more lines. 之后没有更多的行。 So, remove inFile.nextLine() . 因此,删除inFile.nextLine()

Your code should now be: 您的代码现在应为:

 while (inFile.hasNext())        // Use a while loop to read in numbers from the file until the end
    {       
        fileName = inFile.nextLine();

Also, as syb0rg mentioned please refrain from using too many next functions at once. 另外,如syb0rg所述,请避免一次使用过多的下一个功能。 You'd only confuse yourself. 您只会混淆自己。

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

相关问题 获取异常ClassNotFoundException并且不知道为什么 - Getting exception ClassNotFoundException and don't know why 我得到一个ArrayIndexOutOfBounds异常,我不知道为什么。 有人可以解释一下吗? - I'm getting an ArrayIndexOutOfBounds Exception and I don't know why. Can someone shed some light? 我收到“找不到文件”异常,而且我不知道为什么路径正确 - I am getting a File not found exception and I don't know why the path is correct 使数组索引超出范围异常,但不知道为什么? - Getting array index out of bounds exception but don't know why? BufferedReader引发异常,我不知道为什么 - BufferedReader throwing exception and I don't know why 收到 InputMismatch 错误,我不知道为什么 - Getting a InputMismatch error and I don't know why 越界异常,我不知道如何追溯到异常在哪里 - Getting an Out of Bounds exception and I don't know how to trace back to find where the exception is 正在获取错误代码,但不知道为什么 - Getting error code, but don't know why 获取空指针,不知道为什么 - Getting null pointer, don't know why 我应该得到“无效”作为输出,但我得到“有效”作为输出,不知道为什么输出是错误的 - I should be getting "invalid" as output but I'm getting "valid" as output, don't know why the output is wrong
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM