首页 \ 问答 \ 即使存在键,Java HashMap也会返回空值(Java HashMap returning null values even when key is present)

即使存在键,Java HashMap也会返回空值(Java HashMap returning null values even when key is present)

我正在开发一个项目,我们在Map插入键和值对。

如果密钥存在于Map ,我的代码将返回该密钥的值。

但是,即使密钥存在, HashMap也不会返回预期值。

首先,我从文件中读取键和值对,然后我读取另一个与第一个文件具有几乎相同键的文件。

然后我返回一些键的值,但对于其中许多键,值为null

这里是我的代码片段:

Scanner scanner = new Scanner(new FileReader("a.txt"));

LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();

while (scanner.hasNextLine())
{
   String[] columns = scanner.nextLine().split(";");
   map.put(columns[0], columns[1]);
}

System.out.println(map);

for (Map.Entry<String, String> entry : map.entrySet())
{ // name is the input of second file
    if (entry.getKey().equals(name)) 
    {
        num = entry.getValue();         
        fun(num);
    }
}

我的输入文件是

ABC; 1

DEF; 2

GHI; 3

......而名字将是abc

高清


I am working on a project in which we insert key and value pairs in a Map.

If the key is present in the Map, my code returns the value for that key.

However, the HashMap is not returning the expected values, even though the key is present.

First I read the key and value pairs from a file, then I read another file which has almost the same keys as the first file.

Then I return values for some keys, but for many of them the value is null.

Here is a snippet of my code:

Scanner scanner = new Scanner(new FileReader("a.txt"));

LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();

while (scanner.hasNextLine())
{
   String[] columns = scanner.nextLine().split(";");
   map.put(columns[0], columns[1]);
}

System.out.println(map);

for (Map.Entry<String, String> entry : map.entrySet())
{ // name is the input of second file
    if (entry.getKey().equals(name)) 
    {
        num = entry.getValue();         
        fun(num);
    }
}

My input file is

abc;1

def;2

ghi;3

... and name will be abc

def


原文:https://stackoverflow.com/questions/17998097
更新时间:2023-04-29 17:04

最满意答案

恕我直言,你应该首先尝试用铅笔和纸解决问题,然后再开始编码。 Mathworld上的这个链接似乎是一个很好的起点。

编辑: 本页上的文章看起来很有希望。


IMHO you should first try to solve the problem with pencil and paper before you start coding. This link at Mathworld seems to be a good starting point.

EDIT: The article on this page looks promising.

相关问答

更多
  • 恕我直言,你应该首先尝试用铅笔和纸解决问题,然后再开始编码。 Mathworld上的这个链接似乎是一个很好的起点。 编辑: 本页上的文章看起来很有希望。 IMHO you should first try to solve the problem with pencil and paper before you start coding. This link at Mathworld seems to be a good starting point. EDIT: The article on this p ...
  • 您应该在LineSeries上使用这些属性的组合: MarkerStroke="Red" MarkerType="Circle" MarkerStrokeThickness="3" MarkerSize="5" MarkerFill="Transparent" MarkerSize确定半径, MarkerStrokeThickness确定MarkerStrokeThickness的粗细。 请注意,为了在中间获得一个空心圆圈, MarkerStrokeThickness应该小于MarkerSize ...
  • 定义一个由右侧圆圈组成的clipPath ,并将其设置为左侧的clip-path (或相反的方式):
    这个 sqrt( pow( x2 - x1, 2 ) + pow( y2 - y1, 2 ) ) 返回圆心之间的欧氏距离。 作为一个公式,这个距离很简单 sqrt((a1-b1)^2 + (a2-b2)^2) 其中(a1,a2)和(b1,b2)是2个圆的中心。 This sqrt( pow( x2 - x1, 2 ) + pow( y2 - y1, 2 ) ) returns the euclidean distance between the circle centres. As a formula ...
  • 计算几何几乎总是很难实现。 它也几乎总是CPU密集型。 也就是说,如果你设置正确,这个问题只是代数。 计算d = hypot(x2-x1, y2-y1) ,两个中心之间的距离。 如果r1 + r2 < d ,则没有交点。 如果r1+r2 == d ,则交点为(x1, y1) + r1/(r1+r2) * (x2-x1,y2-y1). 如果d < abs(r1-r2) ,则另一个中包含一个圆,并且没有交点。 您可以计算出两个圆相切且一个包含在另一个圆中的情况。 我只会处理其余的案件。 您希望找到与(x2-x1 ...
  • 找到圆的方程。 确保考虑平方根的负数,否则你将只有一个半圆。 设置两个圆的方程等于彼此。 Find the equations of the circles. Make sure to account for the negative of the square root or else you will just have a semi circle. Set the equations of the two circles equal to eachother.
  • // Just take the vector difference between the centers var dx = x2 - x1; var dy = y2 - y1; // compute the length of this vector var L = Math.sqrt(dx*dx + dy*dy); // compute the amount you need to move var step = r1 + r2 - L; // if there is a collision y ...
  • 如果圆的中心之间的距离小于两个半径的总和,则它们重叠。 如果您在真正的距离工作,缩放是不相关的。 If the distance between the centers of the circles is less than the sum of the two radii, then they overlap. Zoom is not relevant if you are working in real distances.
  • 如果点A的顶点坐标是(xa, ya) ,点A的顶点坐标是(xa, ya) (xb, yb) ,点B的顶点坐标是(xa, ya) (xc, yc) ,你可以使用 a = math.sqrt((xb - xc)**2 + (yb - yc)**2) b = math.sqrt((xa - xc)**2 + (ya - yc)**2) c = math.sqrt((xb - xa)**2 + (yb - ya)**2) ra = (b + c - a) / 2 rb = (c + a - b) / 2 rc = ...
  • 如果d(A,B) = sqrt(2)*2*r存在解决方案 要找到解圆的中心,可以绘制圆周,可以将圆与中心(x_m,y_m)相交,即半径为sqrt(2)*r的段AB中点,垂直于AB并从(x_m,y_m)传递的直线 这应该为您提供所有必要的信息,以检查解决方案是否适用,如果是,则绘制它。 A solution exists iff d(A,B) = sqrt(2)*2*r To find the center of the solution circles, that will let you draw the ...

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)