所以我昨天运行了这个程序,不小心在netbeans IDE 7.4中运行了调试器控制台,自从程序停止工作以来。我不知道我的代码中发生了什么变化。
这是错误:
Petname:
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 veterinarian.Veterinarian.main(Veterinarian.java:107)
Java Result: 1
BUILD SUCCESSFUL (total time: 0 seconds)
我添加了一个简单的println语句来查看存储的内容及其null是否为petname。
代码是:
public static void main(String[] args) {
boolean pick = false;
//***************************add file*******************************************
File file = new File("VetList.txt");
//*********************declare ojbects******************************************
try{
Scanner read = new Scanner(file);
int fix = read.nextInt();
do{
for(int x = 0; x < fix; x++){
String petname = read.nextLine();
System.out.println("Petname: " + petname);
int birthday = read.nextInt();
String species = read.next();
double bill = read.nextDouble();
String owner = read.next();
Veterinarian work = new Veterinarian(petname, birthday, species, bill, owner);
Veterinarian.Vet.add(work);
}
}
while(read.hasNextLine() == pick);
}
catch(FileNotFoundException FNF){
System.err.format("File not found");}
txt文件是:
8
hopper
2003
kangaroo
555
Melody_harper
ketty
2009
cat
44
Kitty_katz
Spot
2005
Dog
333
Dottie_Marks
Johnny
2008
cat
111
Misty_waters
Stripper
2011
sckunk
432
Oddie_sweet
Edward
1995
Horse
630
Frieda_gelding
Casper
1998
snake
88
Bo_constricter
boots
2005
Horse
987
Ida_Shuman
我无法更改文件格式以便更好地阅读。
请注意,我已经尝试将java文件本身恢复到此事件之前的时间,但它仍然无法运行并产生相同的错误。我也重新安装了Netbeans。
答案 0 :(得分:0)
如果您将所有数据类型更改为String
并将代码更改为此类
String petname = read.nextLine();
System.out.println("Petname: " + petname);
String birthday = read.next();
String species = read.next();
String bill = read.next();
String owner = read.next();
System.out.println("BirthDay" + birthday);
System.out.println("Name"+petname);
System.out.println("BIll" + bill);
System.out.println("Speci" + species);
System.out.println("Owner " + owner);
你应该得到像
这样的输出 Petname:
BirthDayhopper
Name
BIllkangaroo
Speci2003
Owner 555
这意味着你的生日是一个字符串,但你试图存储为int ..这就是为什么它给出了例外。如果您将代码更改为以下
if (read.hasNext()) {
//if prevents NoSuchElementException
String petname = read.next();
System.out.println("Petname: " + petname);
int birthday = read.nextInt();
String species = read.next();
double bill = read.nextDouble();
String owner = read.next();
System.out.println("BirthDay" + birthday);
System.out.println("Name" + petname);
System.out.println("BIll" + bill);
System.out.println("Speci" + species);
System.out.println("Owner " + owner);
}
您可以获得所需的输出和所需的数据类型。