import java.util.*;
class car{
private int passengers;
private double weight;
private String color;
public void input(){
Scanner sin=new Scanner(System.in);
System.out.println("请输入汽车的载客人数:");
passengers=sin.nextInt();
System.out.println("请输入汽车的重量(吨):");
weight=sin.nextDouble();
System.out.println("请输入汽车的颜色:");
color=sin.next();
}
public int getPassengers() {
return passengers;
}
public void setPassengers(int passengers) {
this.passengers = passengers;
}
public double getWeight() {
return weight;
}
public void setWeight(double weight) {
this.weight = weight;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
}
public class lx2 {
public static void main(String[] args){
car a1=new car();
System.out.println("请输入汽车对象的属性值:");
a1.input();
System.out.println("请输入第一辆车对象的信息如下:");
System.out.println("汽车的载客人数为:"+a1.getPassengers()+";重量为:"+a1.getWeight()+"(吨);颜色为:"+a1.getColor());
car a2=new car();
a2.input();
System.out.println("请输入汽车对象的属性值:");
System.out.println("请输入第一辆车对象的信息如下:");
System.out.println("汽车的载客人数为:"+a2.getPassengers()+";重量为:"+a2.getWeight()+"(吨);颜色为:"+a2.getColor());
}
}
这个代码对吗?谢谢!
对呀,碰到什么问题了吗?这代码没错。
不过既然是封装的练习,那
System.out.println("汽车的载客人数为:"+a1.getPassengers()+";重量为:"+a1.getWeight()+"(吨);颜色为:"+a1.getColor());应该作为一个方法放到类中
class car{
private int passengers;
private double weight;
private String color;
private static int nums = 0;
private String CHN_NUMS[]={"零","一","二"};
public void input(){
nums++;
System.out.println("请输入"+CHN_NUMS[nums]+"汽车对象的属性值:");
Scanner sin=new Scanner(System.in);
System.out.println("请输入汽车的载客人数:");
passengers=sin.nextInt();
System.out.println("请输入汽车的重量(吨):");
weight=sin.nextDouble();
System.out.println("请输入汽车的颜色:");
color=sin.next();
this.print();
}
public void print(){
System.out.println("请输入"+CHN_NUMS[nums]+"汽车对象的信息如下:");
System.out.print("汽车载客人数为:"+this.passengers+";");
System.out.print("重量为"+this.weight+"吨;");
System.out.println("颜色为"+this.color);
}
public int getPassengers() {
return passengers;
}
public void setPassengers(int passengers) {
this.passengers = passengers;
}
public double getWeight() {
return weight;
}
public void setWeight(double weight) {
this.weight = weight;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
}
然后调用
public static void main(String arg[]){
car a1=new car();
a1.input();
car a2=new car();
a2.input();
}
public void input(){
Scanner sin=new Scanner(System.in);
System.out.println("请输入汽车的载客人数:");
passengers=sin.nextInt();
System.out.println("请输入汽车的重量(吨):");
weight=sin.nextDouble();
System.out.println("请输入汽车的颜色:");
color=sin.next();
}
这段代码可以调整一下,set方法赋值。另外应该跟控制台相关的代码应该放到Main方法里面去。