【问题标题】:How do I declare two or more data types on the same line??(New to programming)如何在同一行声明两个或多个数据类型?(编程新手)
【发布时间】:2014-12-09 16:25:35
【问题描述】:

为了简单起见,我很难在同一行上组合两种数据类型...这是我当前的代码:

public class countryPopulations{

    static String zero = "Canada ";
    static String one = "USA ";
    static String two = "China ";

    static double Canada = 35.16;
    static double US = 316.1;
    static double China = 1.357;

    static String million = " million";
    static String billion = " billion";


    public static void main(String[] args){

        System.out.println(zero +Canada + million);
        System.out.println(one +US + million);
        System.out.println(two +China + billion);

    }

}

如您所见,仅在一行上打印“Canada 3516 万”或“US 3.161 亿”就需要做很多工作。我希望我已经包含了足够的信息,如果有人可以提供帮助,那就太好了!此外,如果您有任何其他信息可以分享或关于我刚刚介绍的代码的提示(因为我显然是编程的初学者),那将是很棒的......再次感谢!

【问题讨论】:

标签: java string class types double


【解决方案1】:

您所做的不是组合两种数据类型。 在这种情况下 System.out.println(零+加拿大+百万); 由于 System.out.println 的第一个参数为零,即字符串。 java将做的是将以下参数转换为字符串或 如果它们是对象,它将调用 Object 类中的 toString 方法。

【讨论】:

    【解决方案2】:

    一种可能的选择是使用数组和类似的东西

    String[] countries = { "Canada", "USA", "China" };
    double[] population = { 35.16, 316.1, 1.357 };
    String[] suffix = { "million", "billion" };
    for (int i = 0; i < countries.length; i++) {
        System.out.printf("%s %.3f %s%n", countries[i], population[i],
                (i == 2) ? suffix[1] : suffix[0]);
    }
    

    或者,您可以使用 Country POJO 之类的

    static class Country {
        String name;
        double population;
        boolean billion = false;
    
        public Country(String name, double population, boolean billion) {
            this.name = name;
            this.population = population;
            this.billion = billion;
        }
        public String toString() {
            return String.format("%s %.3f %s", name, population,
                    (billion) ? "billion" : "million");
        }
    }
    
    public static void main(String[] args) {
        Country [] countries = new Country[] {
                new Country("Canada",35.16,false),
                new Country("USA",316.1,false),
                new Country("China",1.357, true)
        };
        for (Country c : countries) {
            System.out.println(c);
        }
    }
    

    【讨论】:

    • 谢谢@Elliott Frisch,什么是 POJO?
    猜你喜欢
    • 1970-01-01
    • 2017-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-18
    • 1970-01-01
    相关资源
    最近更新 更多