[英]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.