所以,我正在编写类代码,但不知道出了什么问题。代码编译,当我输入要搜索的文件时,我收到以下消息:
Enter the name of the file: FanData.txt
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:909)
at java.util.Scanner.next(Scanner.java:1530)
at java.util.Scanner.nextInt(Scanner.java:2160)
at java.util.Scanner.nextInt(Scanner.java:2119)
at FanDriver.fillArray(FanDriver.java:76)
at FanDriver.main(FanDriver.java:35)
按任意键继续 。. .
我使用 TextPad 作为我的编译器,并且文本文件在项目中。以下是我编写的代码(忽略引号中调用的方法,因为它们是我之后需要做的事情):
import java.io.*;
import java.util.Scanner;
public class FanDriver
{
private static Scanner keyboard = new Scanner(System.in);
public static void main(String args[]) throws IOException
{
// Constant for the amount of elements of the array
final int MAXSIZE = 100;
// Declaring variables
int amountFans = 0;
// Declaring and initializing our array of fans
Fan[] fans = new Fan[MAXSIZE];
// Calling all of our methods
amountFans = fillArray(fans, MAXSIZE);
/**
listFanData(fans, amountFans);
bubbleSortByAge(fans, amountFans);
listFanData(fans, amountFans);
bubbleSortByFan(fans, amountFans);
listFanData(fans, amountFans);
searchByAge(fans, amountFans);
searchByFan(fans, amountFans);
*/
}
public static int fillArray(Fan[] array, int MAXSIZE) throws IOException
{
// Declaring variables
int counter = 0;
int age;
String name;
// Getting the file name
System.out.print("\nEnter the name of the file: ");
String fileName = keyboard.nextLine();
// Opening the file
File file = new File(fileName);
Scanner inputFile = new Scanner(file);
// Making sure the file was successfully opened
if (!file.exists())
{
System.out.println("\nERROR: FILE DOESN'T EXIST. CLOSING PROGRAM NOW.");
// Exiting the program
System.exit(0);
}
// Reading all of the amounts from the file
while (inputFile.hasNext() && counter < MAXSIZE)
{
name = inputFile.nextLine();
age = inputFile.nextInt();
array[counter] = new Fan(name, age);
// Adding to our counter
counter = counter + 1;
}
//Closing file
inputFile.close();
return counter;
}
}
我没有 Fan 类的代码,只有类本身。我们正在检索的文件是文件 FanData.txt,它看起来像这样:
Chris P. Cream 5 Scott Free 9 Lou Tenant 3 Trish Fish 12 Ella Mentry 4 Holly Day 3 Robyn DeCradle 12 Annette Funicello 4 Elmo 7 Grover 3 Big Bird 9 Bert 7 Ernie 3 Grover 9
文本文件是逐行的。一行是名称,下一行是数字。我不知道如何在这里正确格式化。任何帮助将不胜感激。