[英]URL data printing trouble
我正在從URL = https://www.cia.gov/library/publications/the-world-factbook/rankorder/rawdata_2151.txt閱讀
我正在嘗試打印出前3個國家/地區,但是每當我嘗試打印出來時,它就會顯示國家總數。 subString或Trim方法可以在這里工作嗎? 只需向寫入方向提示即可。 謝謝
class ButtonTotalListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
if(event.getSource()==printButton){
String line = "";
try{
String address = "https://www.cia.gov/library/publications/the-world-factbook/rankorder/rawdata_2151.txt";
URL pageLocation = new URL(address);
Scanner in = new Scanner(pageLocation.openStream());
while(in.hasNextLine()){
line = in.nextLine();
String [] lineContent = line.split("\\s{2,}");
System.out.println(Arrays.toString(lineContent));
countries.setForeground(Color.YELLOW);
countries.setText(lineContent[2]);
}
}
catch (MalformedURLException ex) {
countries.setText("Country Not Found!");
}
catch (IOException ex) {}
}
您在in.hasNextLine()中遍歷所有國家
您應該引入一個計數器變量並插入一個中斷; 達到限制后,或更改循環條件。
另外,檢查要返回的列。 似乎您從第三列返回數字(即[2]),但是如果要使用國家/地區名稱,則第二列需要[1](數組索引從0開始)。
第三,您如何處理國家/地區? 您設置了文本,但是對於每次循環迭代,您都覆蓋了以前的國家/地區文本(國家/地區是同一變量,在每次迭代中)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.