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

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)。
添加回答
舉報