我正在阅读网址= 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) {}
}
答案 0 :(得分:0)
您可以遍历in.hasNextLine()
中的所有国家/地区你应该引入一个计数器变量并插入一个中断;达到限制后,或更改循环条件。
另外,检查要返回的列。它似乎从thrid列返回数字(这是[2]),但如果你想使用国家名称,你需要[1]第二列(数组索引是从0开始)。
作为第三个,你如何处理国家?您设置文本,但是对于每个循环迭代,您将覆盖以前的国家/地区文本(国家/地区在每次迭代中都是相同的变量)