亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

文本文件包含字符串和數字。如何找到與字符串關聯的最大數字?

文本文件包含字符串和數字。如何找到與字符串關聯的最大數字?

喵喵時光機 2021-11-03 14:27:46
我有一個正在閱讀的文本文件每行都有一對(字符串,值),以逗號分隔。如何找到最大的數字并將其字符串存儲在變量中以備后用?原因是因為我必須將此字符串添加到哈希圖中,以便用戶繼續玩游戲。該文件的大小會有所不同,因此可能會有更多或更少的對。這取決于我的游戲用戶何時想要退出游戲。我唯一的代碼是: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);    }
查看完整描述

2 回答

?
慕慕森

TA貢獻1856條經驗 獲得超17個贊

好的,取一個整數變量并用 0 或最小整數初始化(如果文件有負整數),然后取另一個變量字符串

所以你現在要做的是逐行解析,如果數字大于你的整數變量,把相應的字符串放在字符串變量中;完成文件后,您將擁有最大的整數及其相應的字符串。


查看完整回答
反對 回復 2021-11-03
?
慕森王

TA貢獻1777條經驗 獲得超3個贊

我會這樣做:


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 專家。但它有效;)


查看完整回答
反對 回復 2021-11-03
  • 2 回答
  • 0 關注
  • 181 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號