0
到目前爲止,這是我的代碼。我正在嘗試將文本文件讀入我的演示程序,並將每行分別讀入另一個類。無論出於什麼原因,代碼都會在第一行和下一行之間添加一條空行,這將導致我的程序失敗,因爲nextInt()命令由於空行而讀取一個字符串。任何幫助將不勝感激。多謝你們。讀取文件時輸入不匹配異常
文本文件:
David Wise
USA
SKI HALFPIPE MENS
1
Mike Riddle
Canada
SKI HALFPIPE MENS
2
Kevin Rolland
France
SKI HALFPIPE MENS
3
Maddie Bowman
USA
SKI HALPIPE WOMENS
1
Marie Martinod
France
SKI HALPIPE WOMENS
2
Ayana Onozuka
Japan
SKI HALPIPE WOMENS
3
Felix Loch
Germany
LUGE SINGLE MENS
1
Albert Demchenko
Russia
LUGE SINGLE MENS
2
Armin Zoeggeler
Italy
LUGE SINGLE MENS
3
Natalie Geisenberger
Germany
LUGE SINGLE WOMENS
1
Tatjana Huefner
Germany
LUGE SINGLE WOMENS
2
Erin Hamlin
USA
LUGE SINGLE WOMENS
3
Alexander Tretiakov
Russia
SKELETON MENS
1
Martins Dukurs
Latvia
SKELETON MENS
2
Mathew Antoine
USA
SKELETON MENS
3
Elizabeth Yarnold
United Kingdom
SKELETON WOMENS
1
Noelle Pikus-Pace
USA
SKELETON WOMENS
2
Elena Nikitina
Russia
SKELETON WOMEN
3
Michel Mulder
Russia
500M SPEED SKATING MENS
1
Jan Smeekens
Russia
500M SPEED SKATING MENS
2
Ronald Mulder
Russia
500M SPEED SKATING MENS
3
演示程序:
import java.io.*;
import java.util.*;
import ch06.lists.*;
import support.*;
public class OlympicDemo
{
public static void main(String[] args)
{
ListInterface<String> list = new ArrayIndexedList<String>();
final String FILEINNAME = "src/AthleteInformation.txt";
String name = "";
String country = "";
String event = "";
int rank = 0;
Athlete athletes;
OlympicAthletes olympic;
try
{
FileReader file = new FileReader(FILEINNAME);
Scanner ath = new Scanner(file);
while(ath.hasNext())
{
name = ath.nextLine();
System.out.println(name);
country = ath.nextLine();
System.out.println(country);
event = ath.nextLine();
System.out.println(event);
rank = ath.nextInt();
System.out.println(rank);
athletes = new Athlete(name, country, event, rank);
}
}
catch(FileNotFoundException e)
{
System.out.println("FILE: " + FILEINNAME + " DOES NOT EXIST");
}
/**
try
{
ObjectInputStream in = new ObjectInputStream(new
FileInputStream(FILEINNAME));
athletes = (Athlete)in.readObject();
}
catch(Exception e)
{
System.out.println("FILE: " + FILEINNAME + " DOES NOT EXIST");
}
*/
}
}
OUTPUT:
David Wise
USA
SKI HALFPIPE MENS
1
Mike Riddle
Canada
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at OlympicDemo.main(OlympicDemo.java:34)
工作過,非常感謝您的幫助! – Deigs 2014-11-23 00:22:30