Java 读取文本文件并通过HashMap获取距离值
我发现这个文本文件(dis.txt)包含: 这些数字是距离,例如A和Z之间的距离是75 我习惯于用java程序阅读这些距离和城市,比如(Z75)(T118)(S140),我认为HashMap在我创建HashMap之后对我的问题有好处,正如你们看到的,我写了myMap.get(“A”);我不会给我结果(Z75)(T118)(S140)。 我希望你能理解我的问题,谢谢Java 读取文本文件并通过HashMap获取距离值,java,Java,我发现这个文本文件(dis.txt)包含: 这些数字是距离,例如A和Z之间的距离是75 我习惯于用java程序阅读这些距离和城市,比如(Z75)(T118)(S140),我认为HashMap在我创建HashMap之后对我的问题有好处,正如你们看到的,我写了myMap.get(“A”);我不会给我结果(Z75)(T118)(S140)。 我希望你能理解我的问题,谢谢 import java.io.FileInputStream; import java.util.HashMap;
import java.io.FileInputStream;
import java.util.HashMap;
import java.util.Properties;
public class nodes {
public static void main(String[] args) {
Properties pro = new Properties();
{
try {
pro.load(new FileInputStream("dis"));
} catch (Exception e) {
System.out.println(e.toString());
}
for (int i = 0; i <= 13; i++) {
String abu = pro.getProperty("" + i);
//System.out.println(abu);
}
HashMap<String, String> myMap = new HashMap<String, String>();
myMap.get("A");
myMap.get("B");
myMap.get("C");
myMap.get("D");
System.out.println(myMap.get("A"));
System.out.println(myMap.get("B"));
System.out.println(myMap.get("C"));
System.out.println(myMap.get("D"));
}
}
}
import java.io.FileInputStream;
导入java.util.HashMap;
导入java.util.Properties;
公共类节点{
公共静态void main(字符串[]args){
Properties pro=新属性();
{
试一试{
专业加载(新文件输入流(“dis”);
}捕获(例外e){
System.out.println(例如toString());
}
对于(inti=0;i当然,在从HashMap中获取任何数据之前,您需要填充HashMap
在循环中读取每个属性的值,将数据放入映射中。
对于LHS
上的reference类型
,请始终使用abstract
类型。使用Map
而不是HashMap
Map<String, String> myMap = new HashMap<String, String>();
for (int i = 1; i <= 13; i++) { // Start loop from 1, as properties in txt file are from 1
String abu = pro.getProperty("" + i);
// Split the string on space, and put 1st and 2nd element of array
// as `key-value` pair in HashMap
String[] arr = abu.split(" ");
myMap.put(arr[0], arr[1]);
}
// Now you can fetch the data
for (String str: myMap.keySet()) {
System.out.println(myMap.get(str));
}
Map myMap=newhashmap();
对于(inti=1;i)这是针对AI(人工智能)project by Java你在哪里填充了你的hashmap???。我看不到任何代码:但是我创建了mymap byhashMap@jangiz..仅仅创建一个映射,并不会将您的值存储到其中。您实际上需要填充它。对不起,我不明白您的意思。您能解释得更清楚吗?好的,您的abu
字符串包含什么?它不包含:-“A(Z75)(T118)(S140)”
?打印它并查看它包含的内容。您获得NPE是因为您的循环以0
开始,并且您的文件中没有0
的属性。使用1
开始您的循环。它可以工作。没有错误,但程序不会运行,因为此代码字符串[]arr=abu.split(“”);在异常中,此错误异常出现在线程“main”java.lang.NullPointerException at nodes.main(nodes.java:30)@jangiz中。是的,请参阅我编辑的代码以删除该错误。请参阅我以前的注释中的原因。您是对的,在我更改0-->1后,结果中的这些无任何错误和无输出显示为空值
Map<String, String> myMap = new HashMap<String, String>();
for (int i = 1; i <= 13; i++) { // Start loop from 1, as properties in txt file are from 1
String abu = pro.getProperty("" + i);
// Split the string on space, and put 1st and 2nd element of array
// as `key-value` pair in HashMap
String[] arr = abu.split(" ");
myMap.put(arr[0], arr[1]);
}
// Now you can fetch the data
for (String str: myMap.keySet()) {
System.out.println(myMap.get(str));
}