【问题标题】:Getting InputMismatchException When Reading Text File into Integer Array将文本文件读入整数数组时出现 InputMismatchException
【发布时间】:2014-09-09 18:26:26
【问题描述】:

我正在将一个用数字(在单独的行上)填充的文本文件读入一个整数数组。我以为我写的程序很好,但是当我尝试运行它时遇到了问题。 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()

}

【问题讨论】:

  • 我认为,您可能在输入文件的末尾有一个空行,它无法转换为int,因此抛出异常。从文件中删除任何空行,或者将它们作为字符串读取并检查它们是否为空白或删除任何尾随空格,然后执行Integer.parseInt()

标签: java arrays file-io integer


【解决方案1】:

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

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() void 中添加了一个 try/catch 块,该块捕获 NoSuchElementException,其中包括 InputMismatchException,从而防止尝试添加任何非整数。我希望这能解决你的问题!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-03
    • 2017-07-16
    相关资源
    最近更新 更多