为了简单起见,我很难在同一行上组合两种数据类型......这是我当前的代码:
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);
}
}
正如你所看到的那样,只需印刷加拿大3516万和#34;在一条线上,或者" US311.1百万"。我希望我已经包含了足够的信息,如果有人能提供帮助那就太棒了!此外,如果您有任何可以分享的其他信息或者我刚才提供的代码提示(因为我显然是编程的初学者),那将是非常棒的...再次感谢!
答案 0 :(得分:0)
一种可能的选择是使用数组,类似
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);
}
}
答案 1 :(得分:0)
您正在做的不是组合两种数据类型。 在这种情况下 System.out.println(零+加拿大+百万); 由于您对System.out.println的第一个参数为零,因此为字符串。 java将要做的是将以下参数转换为string或 如果它们是对象,它将在Object类中调用toString方法。