将文本文件读入整数数组时获取InputMismatchException

时间:2014-09-09 18:26:26

标签: java arrays file-io integer

我正在读取一个填充了数字(在各行上)的文本文件到一个整数数组中。我以为我编写的程序很好,但是当我尝试运行它时遇到了问题。 Netbeans告诉我" InputMismatchException。"我认为这个问题位于我的第二个名为readTxtFile的方法中,特别是while循环。任何帮助将不胜感激。

package arrayspa;
import java.util.Scanner;

public class ArraysPA {

/**
 * Using the enrollment.txt file, count and display the number of full
 * sections and the percentage of the sections that are full. A section is
 * full if it contains 36 students.
 */
public static void main(String[] args) throws Exception 
{
    //an array to hold total # of students in each section
    int[] numStud = new int[100];
    int count; //number of elements actually used
    int fullSections; //number of full sections (36 enrolled students)
    int percent; //percentage of sections that are full

    //read data into numStud[] from txt file
    count = readTxtFile(numStud);

    //print the array on the screen
    System.out.println("The original file:");
    displayLines(numStud,count);

    //calculate number of sections that are full and display number
    fullSections = calcFullSections(numStud, count);
    System.out.println("There are "+fullSections+ "full sections.");

    //display percentage of sections that are full
    percent = fullSections/count;
    System.out.println("The percentage of sections that are full is " 
            +percent);

} //end main()

/**
 * This methods read data from enrollment.txt (located in project folder)
 * line by line into an integer array. It then uses an if statement to 
 * display the total number of full sections (a section is considered full
 * if there are 36 students enrolled).
 */
public static int readTxtFile(int[] numStud) throws Exception
{
    int i=0; //number of elements in array initialized to zero

    //Create File class object linked to enrollment.txt
    java.io.File enrollment = new java.io.File("enrollment.txt");

    //Create a Scanner named infile to read input stream from file
    Scanner infile = new Scanner(enrollment);

    /**Create while loop to read lines of text into array. It uses the
     *Scanner class boolean function hasNextLine() to see if there is
     *another line in the file.
     */ 
    while (infile.hasNextLine())
    {
        //read a line and put it in an array element
        numStud[i] = infile.nextInt();
        i ++; //increment the number of array elements
    } //end while

    infile.close();
    return i; //returns number of items used in the array
} //end readTxtFile(int[] numStud

public static void displayLines(int[] lines, int count)
{
    int i; //loop counter

    // iterate the elements actually used
    for (i=0; i < count; i++)
        System.out.println(lines[i]);
} //end displayLines()

public static int calcFullSections(int[] numStud, int count)
{
    int fullSections=0; //number of full sections
    int i;            //loop counter

    for (i=0; i < count; i++)
        if (numStud[i]==36)
        {
            fullSections = fullSections + 1;
        }

    return fullSections;   
} //end calcFullSections()

}

1 个答案:

答案 0 :(得分:0)

当输入与您要写入的变量类型不匹配时,抛出InputMismatchException。我已经测试了你的代码,它似乎工作正常,除非文件&#34; enrollment.txt&#34;有一个空行或空格。我已经测试过在文件末尾添加一个空行并运行它,我收到了NoSuchElementException,所以问题可能是文件中某处的空行或非整数。要解决此问题,您可以删除文件中的任何空白行/非整数,或者,您最好通过捕获readTxtFile()来修改NoSuchElementException方法以忽略空行,如下所示:< / p>

public static int readTxtFile(int[] numStud) throws Exception
{
int i=0; //number of elements in array initialized to zero

//Create File class object linked to enrollment.txt
java.io.File enrollment = new java.io.File("enrollment.txt");

//Create a Scanner named infile to read input stream from file
Scanner infile = new Scanner(enrollment);

/**Create while loop to read lines of text into array. It uses the
 *Scanner class boolean function hasNextLine() to see if there is
 *another line in the file.
 */ 
while (infile.hasNextLine())
{
    // Add this try/catch block to prevent reading blank line
    try {
        numStud[i] = infile.nextInt();
        i ++; 
    } catch (NoSuchElementException e) {
    }
} //end while

infile.close();
return i; //returns number of items used in the array
} //end readTxtFile(int[] numStud

正如您所看到的,我在readTxtFile()空格中添加了一个try / catch块,其中包含NoSuchElementException,其中包含InputMismatchException,阻止尝试添加任何非{整数。我希望这能解决你的问题!