[英]If within a loop not working as expected java
我正在从文本文件(“ text.txt”)中读取行,然后将其存储到树形图中,直到出现apply一词。
但是,执行此操作后,我在树形图中没有最后一行“ 4 apply”
的text.txt
1添加
3倍
4申请
6添加
Scanner input = new Scanner(file);
while(input.hasNextLine()){
String line = input.nextLine();
String[] divline = line.split(" ");
TreeMap<Integer, String> Values = new TreeMap();
if(!divline[1].equals("apply"))
{
Values.put(Integer.valueOf(divline[0]), divline[1]);
}
else
{
Values.put(Integer.valueOf(divline[0]), divline[1]);
break;
}
System.out.println(Values);
}
您每次都在while循环内创建新地图。 将以下代码放在while循环之前。
TreeMap<Integer, String> valores = new TreeMap();
同样,地图内容的打印也需要纠正。 所以你的最终代码可以是
Scanner input = new Scanner(file);
TreeMap<Integer, String> valores = new TreeMap();
while(input.hasNextLine()){
String line = input.nextLine();
String[] divline = line.split(" ");
if(!divline[1].equals("apply")){
valores.put(Integer.valueOf(divline[0]), divline[1]);
} else {
valores.put(Integer.valueOf(divline[0]), divline[1]);
break;
}
}
for (Entry<Integer,String> entry: valores){
System.out.println(entry.getKey() + "- "+entry.getValue());
}
4 apply
被添加到valores
映射中,但未得到打印,因为您在print语句之前脱离了循环。
另外,您可能需要在while
循环之前移动valores
映射的创建。 并循环打印后。
TreeMap<Integer, String> valores = new TreeMap();
while(input.hasNextLine()){
String line = input.nextLine();
String[] divline = line.split(" ");
if(!divline[1].equals("apply")){
valores.put(Integer.valueOf(divline[0]), divline[1]);
} else {
valores.put(Integer.valueOf(divline[0]), divline[1]);
break;
}
}
System.out.println(valores);
您正在为每一行创建一个新的“ valores” TreeMap
,然后打印包含该行的TreeMap
。 在“应用”的情况下,您将执行相同的操作,即创建一个新的映射,然后将值放在此处-仅通过破坏即可跳过System.out.println
部分。
您需要将TreeMap的声明放在while之前。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.