【发布时间】:2014-04-12 17:38:48
【问题描述】:
我目前正在开发游戏风险。在构建国家、大洲及其邻接关系的 Board 课程中,我正在阅读三个不同的文本文件。当我构建一个新大陆时,它的构造函数期望以下 (字符串名称、int bonusArmies、ArrayList memberCountries)。 现在,我正在使用扫描仪从这样组织的文本文件中读取, 它拥有的名称、奖金军队,以及每条线上的其余部分是它的成员国。
北美,5,阿拉斯加,阿尔伯塔,中美洲,美国东部,格陵兰,西北地区,安大略,魁北克,美国西部 南美,2,阿根廷,巴西,委内瑞拉 欧洲,5,英国,冰岛,北欧,斯堪的纳维亚,南欧,乌克兰,西欧 非洲,3,刚果,东非,埃及,马达加斯加,北非,南非 亚洲,7,阿富汗,中国,印度,伊尔库茨克,日本,堪察加,中东,蒙古,暹罗,西伯利亚,乌拉尔,雅库茨克 澳大利亚,2,东澳大利亚,印度尼西亚,LotR,新几内亚,西澳大利亚
我知道我需要为 Scanner 设置分隔符,我尝试了多种方法,但无济于事。这是我尝试创建 Continents 哈希图的示例。
public void createContinents()
{
Scanner inputTwo = new Scanner( new File( "continents.txt");
while( inputTwo.hasNext()) //continues to create and add countries until their are none next
{
String line = inputTwo.nextLine(); //stores the entire line
Scanner lineScan = new Scanner( line); //passes the entire line into Scanner
lineScan.useDelimiter(","); //sets the Scanner's delimiter pattern
String name = inputTwo.next(); //stores the first String which is the name of the current continent being created
System.out.println( " the name is" + name);
int bonusArmies = inputTwo.nextInt(); //stores the second String which is casted into an int for the continent bonus armies
System.out.println(" the number of bonus armies is" + bonusArmies);
ArrayList<Country> memberCountries = new ArrayList<Country>(); //creates an arraylist to hold the member countries of current continent
while( inputTwo.hasNext()) //goes through the rest of the line to add the member countries until it reaches the end of the line
{
memberCountries.add( countries.get(inputTwo.next()));//gets string name of country and pass it as key to store into temp arraylist of countries
System.out.println( "the member countries" + memberCountries);
}
continent = new Continent( name, bonusArmies, memberCountries); //creates continent
continents.put(name , continent); //associates a key to the current continent
}
inputTwo.close();
}
这是该图像中的文本。
PS C:\Users\repti_000\desktop\risk\homeworks2120\game> java BoardTester
the name is
SouthAmerica,2,Argentina,Brazil,Venezuela
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 Board.createContinents(Board.java:66)
at Board.loadBoard(Board.java:141)
at Board.<init>(Board.java:27)
at BoardTester.main(BoardTester.java:7)
PS C:\Users\repti_000\desktop\risk\homeworks2120\game>
【问题讨论】:
-
请描述实际行为以及不受欢迎的原因。
-
您忘记关闭
new Scanner();。成功:Scanner inputTwo = new Scanner( new File( "continents.txt"));
标签: java file-io hashmap java.util.scanner delimiter