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

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

使用 ArrayList 和掃描儀從文本文件中打印特定數字

使用 ArrayList 和掃描儀從文本文件中打印特定數字

千萬里不及你 2022-09-07 17:16:23
我需要通過使用掃描儀鍵入數字從文本文件中獲取特定數字。該程序需要能夠將多個數字相加。示例 如果我鍵入1,那么我將得到數字80。在我鍵入2之后,我會得到數字85,然后將兩個數字相加。結果 80 + 85 = 165。我的文本文件如下所示:180285350我能夠打印文本文件中的所有數字并將其放入ArrayList,但我需要打印出一個特定的數字。
查看完整描述

2 回答

?
不負相思意

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

您可以讀取所有 txt 文件數據并將其存儲在鍵值對中的映射中。鍵將是數字索引,值將是實際數字。然后從 map 中獲取密鑰并添加它們各自的值。代碼將如下所示:


public class NumberRead{

    public static String readFileAsString(String fileName)throws Exception 

    { 

        String data = ""; 

        data = new String(Files.readAllBytes(Paths.get(fileName))); 

        return data; 

    } 


    public static void main(String[] args) throws Exception {

        HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();

        String data = readFileAsString("-----Your Numbers.txt Path-----"); 

        String[] split = data.split("\\s+");

        for(int i=0;i<split.length;i++) {

            if(i%2==0) {

                map.put(Integer.parseInt(split[i]), Integer.parseInt(split[i+1]));

            }

        }

        Scanner sc = new Scanner(System.in);

        System.out.println("Enter First Number Index");

        int first = sc.nextInt(); 

        System.out.println("Enter Secound Number Index");

        int second = sc.nextInt();


        if(map.containsKey(first)&&map.containsKey(second)) {

            System.out.println("Addition is: "+((map.get(first))+map.get(second)));

        } else {

            System.out.println("Indexes are not present");

        }

        sc.close();

    }

}

您的 Numbers .txt 文件應采用以下格式:


1 80

2 85

3 50

4 95

5 75


查看完整回答
反對 回復 2022-09-07
?
慕婉清6462132

TA貢獻1804條經驗 獲得超2個贊

不要使用數組列表,而是在java的HashMap(鍵值對)中使用并存儲它。


HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();

map.put(1,80);

map.put(2,85);

// To retrieve the values 

map.get(2); // returns 85 

因此,值的檢索很容易,并且復雜性為O(1)。


查看完整回答
反對 回復 2022-09-07
  • 2 回答
  • 0 關注
  • 102 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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