编写手机类(MobilePhone),含有type(型号,String类型)、price(孢格,int类型)孨性,敩链表中添孧n孿手机孡象(从键盘输入)
时间: 2023-06-20 21:06:14 浏览: 151
下面是Java语言的MobilePhone类的代码实现:
```java
import java.util.LinkedList;
import java.util.Scanner;
public class MobilePhone {
private String type;
private int price;
public MobilePhone(String type, int price) {
this.type = type;
this.price = price;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public static void main(String[] args) {
LinkedList<MobilePhone> phoneList = new LinkedList<>();
Scanner scanner = new Scanner(System.in);
System.out.print("请输入手机数量:");
int n = scanner.nextInt();
for (int i = 0; i < n; i++) {
System.out.print("请输入第" + (i + 1) + "部手机的型号:");
String type = scanner.next();
System.out.print("请输入第" + (i + 1) + "部手机的价格:");
int price = scanner.nextInt();
phoneList.add(new MobilePhone(type, price));
}
System.out.println("您输入的手机信息如下:");
for (int i = 0; i < phoneList.size(); i++) {
MobilePhone phone = phoneList.get(i);
System.out.println("型号:" + phone.getType() + ",价格:" + phone.getPrice());
}
}
}
```
在上面的代码中,我们定义了MobilePhone类,包含型号和价格两个属性,以及相应的getter和setter方法。在main方法中,我们通过Scanner从键盘输入手机数量和每个手机的型号和价格,并将其添加到LinkedList中。最后,输出所有手机的信息。
阅读全文