问题在下面。这是代码: 程序的简短说明:我做了两节课。在飞机类中,我定义了每架飞机的属性。在Main类中,我为Airplane类创建了对象(这些对象是飞机)。目的是程序打印出所要求飞机的规格。
public class Main {
public static void main(String[] args) {
Airplane a320 = new Airplane();
Airplane a747 = new Airplane();
Airplane avro85 = new Airplane();
Airplane a380 = new Airplane();
a320.type = "Airbus 320";
a320.idNumber = 1;
a320.seats = 165;
a320.velocity = 890;
a320.range = 12600.00;
a747.type = "Boeing 747";
a747.idNumber = 2;
a747.seats = 436;
a747.velocity = 907;
a747.range = 13700.00;
avro85.type = "Avro RJ 85";
avro85.idNumber = 3;
avro85.seats = 93;
avro85.velocity = 760;
avro85.range = 2200.00;
a380.type = "Airbus 380";
a380.idNumber = 4;
a380.seats = 516;
a380.velocity = 907;
a380.range = 12000.00;
a380.printInfo(); //WHY DOES THIS ONLY PRINT THE TYPE???
}
}
public class Airplane {
String type;
int idNumber;
int seats;
double velocity;
double range;
public void printInfo() {
System.out.printf(this.type, this.idNumber, this.seats, this.velocity, this.range);
}
}
问题:1)为什么我必须写System.out.prinf();
而不是`System.out.println();? 2)当我运行程序时,它会编译。那样就好。但这只将属性“ type”打印出来。如何更改打印所有规格的程序?
在此之前,我感谢您的所有回答。如果您还可以向我解释代码失败的原因,那就太好了。
谢谢。
答案 0 :(得分:2)
答案1:
首先,您必须了解println和printf的区别。 名称是其功能的缩写。 println 是“打印行”的缩写,表示在打印参数后转到下一行。 printf 是打印格式化程序的缩写,它使您能够标记String变量将在何处传递并随同传递这些变量。这省去了进行长字符串连接的麻烦。这是一些示例,我将在计算机的左侧放置“ _”,并在发送另一个打印语句时将其放置在其中。
println语句:
System.out.println("Happy New year 2020!");
结果在控制台中显示给用户:
Happy New year 2020!
_
printf声明:
String var_year = "2020"
System.out.printf("Happy New year %s!", var_year);
结果在控制台中显示给用户:
Happy New year 2020!_
因为您使用的是printf语句,所以它只打印“ type”属性而忽略其余属性。
答案2: 您可以使用println并更改代码,例如:
System.out.printf(this.type +" "+ this.idNumber +" "+ this.seats +" "+ this.velocity +" "+ this.range);
我想你可以使你的上述陈述更具描述性。
答案 1 :(得分:0)
您不必编写printf,可以使用println,但必须替换为“ +”而不是“,”。