[英]Text file contains strings and numbers. How do I find the largest number associated with the string?
我有一個正在讀取的文本文件
每行都有一對(字符串,值),以逗號分隔。 如何找到最大的數字並將其字符串存儲在變量中以備后用? 原因是因為我必須將此字符串添加到哈希圖中,以便用戶繼續玩游戲。 文件大小會有所不同,因此可能會有更多對或更少。 這取決於我的游戲用戶何時退出游戲。
我為此唯一的代碼是:
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);
}
確定接受一個整數變量並用0或最小整數初始化(如果文件具有負整數),然后接受另一個變量字符串
因此,您現在想要做的是逐行解析,如果number大於您的整數變量,則將相應的字符串放入string變量中; 處理完文件后,您將擁有最大的整數及其對應的字符串。
我會這樣:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
String result = "";
int temp = 0;
String line = "";
String path = "C:\\Users\\marco\\IdeaProjects\\untitled1\\src\\test.txt";
try {
java.io.BufferedReader fr = new java.io.BufferedReader(new java.io.FileReader(new File(path)));
while ((line = fr.readLine()) != null) {
String[] splitted = line.split(",");
if(Integer.parseInt(splitted[1]) > temp){
temp = Integer.parseInt(splitted[1]);
result = line;
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(result);
}
}
我不是Java專家。 但這有效;)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.