【发布时间】: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