我有一个正在阅读的文本文件
每行都有一对(字符串,值),以逗号分隔。如何找到最大的数字并将其字符串存储在变量中以备后用?原因是因为我必须将此字符串添加到哈希图中,以便用户继续玩游戏。该文件的大小会有所不同,因此可能会有更多或更少的对。这取决于我的游戏用户何时想要退出游戏。
我唯一的代码是:
try
{
File savedGame=new File("savedGame.txt");
Scanner scan=new Scanner(savedGame);
//something goes here?
}
catch(FileNotFoundException fileError)
{
System.out.println("The file was not Found!\n " + "ERROR:" + fileError);
}
更新:VIPER 对此的方法是实现我所需要的最干净的方法。
我的代码现在是:
try
{
int largest=0;
String startingStr="";
File savedGame=new File("savedGame.txt");
Scanner scan=new Scanner(savedGame);
while(scan.hasNext())
{
String line=scan.nextLine();
String tokens[]=line.split(",");
if(Integer.parseInt(tokens[1])>largest)
{
largest=Integer.parseInt(tokens[1]);
startingStr=tokens[0];
}
}
}
catch(FileNotFoundException fileError)
{
System.out.println("The file was not Found!\n " + "ERROR:" + fileError);
}
慕慕森
慕森王
相关分类