简体   繁体   English

使用 ArrayList 和扫描仪从文本文件中打印特定数字

[英]Print specific number from text file using an ArrayList and scanner

I need to get a specific number out from a text file by typing a number using a scanner.我需要通过使用扫描仪输入数字来从文本文件中获取特定数字。 The program needs to be able to add multiple numbers together.该程序需要能够将多个数字相加。

Example If i type 1 then I would get the number 80. And after I type 2 then I would get the number 85 and then adding the two numbers together.示例 如果我输入 1 那么我会得到数字 80。在我输入 2 之后我会得到数字 85 然后将两个数字相加。 Result 80 + 85 = 165.结果 80 + 85 = 165。

My text file looks like this:我的文本文件如下所示:

1
80

2
85

3
50

I am able to print all the numbers from my text file and getting it in to an ArrayList but I need to get a specific number printed out.我能够打印文本文件中的所有数字并将其放入 ArrayList,但我需要打印出特定数字。

Instead of using Array list, use and store it in HashMap(key value pair) in java.不使用数组列表,而是在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 

So that retrieval of values is easy and complexity O(1).因此,检索值很容易,复杂度为 O(1)。

You can Read all the txt file data and stored it into the Map in Key value pair.您可以读取所有txt文件数据并将其存储到Key值对中的Map中。 Key will be Number index and Value will be actual number.键将是数字索引,值将是实际数字。 Then fetch the keys from map and add their respective values.然后从地图中获取键并添加它们各自的值。 Code will look like:代码将如下所示:

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();
    }
}

And your Numbers.txt file should be in following format:您的 Numbers.txt 文件应采用以下格式:

1 80
2 85
3 50
4 95
5 75

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM