【问题标题】:Java Database Display all Country Info from Country Database TableJava 数据库显示国家数据库表中的所有国家信息
【发布时间】:2015-05-13 02:19:00
【问题描述】:

我正在处理一项需要更改 Country 类的 Java 任务,以便它打印国家数据库表中的每个国家,而不仅仅是一个国家。我尝试了各种实例,但无法让它显示所有实例。我对 Java 很陌生,所以我知道我以某种方式弄乱了语法,或者它公然在我面前,我已经研究这个太久了,需要另一双眼睛。到目前为止,这是我从国家表中显示一个国家的内容。

    public class CountryMain {
    public static void main(String[] args) {
        ReadCountryDB rcdb = new ReadCountryDB();
        List<Country> countries = rcdb.getCountries();

        Country firstCountry = countries.get(0);
        System.out.println("First country:");
        System.out.println("Name: " + firstCountry.getName()
                           + "  Population: " + firstCountry.getPopulation()
                           + "  Median Age: " + firstCountry.getMedianAge());
      }
}

我知道我需要更改的“Country firstCountry = countries.get(0)”方法部分,我尝试过未定义的 getAll,但我对需要定义的内容感到困惑,所以它拉国家数据库中的所有内容。

非常感谢您对此的任何帮助。

【问题讨论】:

  • 使用for loop ?

标签: java arrays class sorting methods


【解决方案1】:

如果您在countries 列表中获得了正确的计数,那么您可以遍历列表以将每个元素作为 -

for (Country country : countries) {
  System.out.println("Name: " + country.getName()
                       + "  Population: " + country.getPopulation()
                       + "  Median Age: " + country.getMedianAge());
}

【讨论】:

    【解决方案2】:

    如果您已经通过rcdb.getCountries() 拉出了所有国家/地区,那么只需使用循环打印出所有国家/地区:

    for (Country country : countries) {   
         System.out.println("Country:");
         System.out.println("Name: " + country.getName()
                           + "  Population: " + country.getPopulation()
                           + "  Median Age: " + country.getMedianAge());
    }
    

    【讨论】:

      【解决方案3】:

      循环播放

         public class CountryMain {
          public static void main(String[] args) {
          ReadCountryDB rcdb = new ReadCountryDB();
          List<Country> countries = rcdb.getCountries();
          for(int i=0; i<coutries.size; i++){
           Country firstCountry = countries.get(i);
           System.out.println("First country:");
           System.out.println("Name: " + firstCountry.getName()
                             + "  Population: " + firstCountry.getPopulation()
                             + "  Median Age: " + firstCountry.getMedianAge());
          }
        }
      }
      

      【讨论】:

        猜你喜欢
        • 2018-10-16
        • 2011-05-25
        • 2014-12-19
        • 1970-01-01
        • 2013-12-13
        • 1970-01-01
        • 2018-03-18
        • 2013-01-19
        • 2011-03-23
        相关资源
        最近更新 更多