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

我需要通过使用扫描仪键入数字从文本文件中获取特定数字。该程序需要能够将多个数字相加。


示例 如果我键入1,那么我将得到数字80。在我键入2之后,我会得到数字85,然后将两个数字相加。结果 80 + 85 = 165。


我的文本文件如下所示:


1

80


2

85


3

50

我能够打印文本文件中的所有数字并将其放入ArrayList,但我需要打印出一个特定的数字。


千万里不及你
浏览 87回答 2
2回答

不负相思意

您可以读取所有 txt 文件数据并将其存储在键值对中的映射中。键将是数字索引,值将是实际数字。然后从 map 中获取密钥并添加它们各自的值。代码将如下所示:public class NumberRead{&nbsp; &nbsp; public static String readFileAsString(String fileName)throws Exception&nbsp;&nbsp; &nbsp; {&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; String data = "";&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; data = new String(Files.readAllBytes(Paths.get(fileName)));&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; return data;&nbsp;&nbsp; &nbsp; }&nbsp;&nbsp; &nbsp; public static void main(String[] args) throws Exception {&nbsp; &nbsp; &nbsp; &nbsp; HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();&nbsp; &nbsp; &nbsp; &nbsp; String data = readFileAsString("-----Your Numbers.txt Path-----");&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; String[] split = data.split("\\s+");&nbsp; &nbsp; &nbsp; &nbsp; for(int i=0;i<split.length;i++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(i%2==0) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; map.put(Integer.parseInt(split[i]), Integer.parseInt(split[i+1]));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; Scanner sc = new Scanner(System.in);&nbsp; &nbsp; &nbsp; &nbsp; System.out.println("Enter First Number Index");&nbsp; &nbsp; &nbsp; &nbsp; int first = sc.nextInt();&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; System.out.println("Enter Secound Number Index");&nbsp; &nbsp; &nbsp; &nbsp; int second = sc.nextInt();&nbsp; &nbsp; &nbsp; &nbsp; if(map.containsKey(first)&&map.containsKey(second)) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println("Addition is: "+((map.get(first))+map.get(second)));&nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println("Indexes are not present");&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; sc.close();&nbsp; &nbsp; }}您的 Numbers .txt 文件应采用以下格式:1 802 853 504 955 75

慕婉清6462132

不要使用数组列表,而是在java的HashMap(键值对)中使用并存储它。HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();map.put(1,80);map.put(2,85);// To retrieve the values&nbsp;map.get(2); // returns 85&nbsp;因此,值的检索很容易,并且复杂性为O(1)。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java