刚刚入驻本论坛,还不太懂.希望各大神多照顾.这是今天刚学习的小项目,拿出来和大家分享一下.同时也让自己在加深了解.
import java.util.ArrayList;
import java.util.Scanner;
public class MyFruit3
{
public static void main(String[] args)
{
//创建存储所有水果的集合对象 看到集合就看到所有的水果
ArrayList<Fruit> list = new ArrayList<Fruit>();
//调用init方法 为集合添加数据
init(list);
//调用添加水果方法
addFruit(list);
// Fruit ll = list.get(0);
// Fruit pg = list.get(1);
// Fruit mht = list.get(2);
//打印水果报价单
System.out.println("水果编号 水果名称 水果单价 计价单位");
//遍历水果集合,依次获取每个水果,打印每个水果的属性
for(int i= 0 ;i<list.size();i++){
Fruit thisFruit = list.get(i);
System.out.println(" "+thisFruit.id+" "+thisFruit.name+" "+thisFruit.price+" "+thisFruit.unit);
}
}
//定义一个方法 为集合添加元素 方法名init 参数 ArrayList<Fruit> list 返回值 void
public static void init(ArrayList<Fruit> list){
//创建一个Fruit对象榴莲
Fruit ll = new Fruit();
ll.id = 1;
ll.name = "榴莲";
ll.price = 32.0;
ll.unit = "公斤";
//创建Fruit对象苹果
Fruit pg = new Fruit();
pg.id = 2;
pg.name = "苹果";
pg.price = 6.5;
pg.unit = "公斤";
//创建Fruit对象 猕猴桃
Fruit mht = new Fruit();
mht.id = 3;
mht.name = "猕猴桃";
mht.price = 6.0;
mht.unit = "公斤";
Fruit rsg = new Fruit();
rsg.id = 4;
rsg.name = "人参果";
rsg.price = 10000.0;
rsg.unit = "克";
//将对象添加到集合中
list.add(ll);
list.add(pg);
list.add(mht);
list.add(rsg);
}
//定义方法 键盘录入水果 添加到集合中 方法名 addFruit 参数 ArrayList<Fruit> list 返回值 void
/*
创建一个水果对象
提示用户输入新商品编号
接收用户输入的新商品编号
提示用户输入其他信息
接收用户输入的其他信息
将新水果添加到集合中
*/
public static void addFruit(ArrayList<Fruit> list){
//创建新水果的对象
Fruit newFruit = new Fruit();
System.out.println("请输入新水果的编号:");
//调用enterNumber方法 接收用户输入的新水果编号
newFruit.id= enterNumber();
System.out.println("请输入新水果的名称: ");
//调用enterString方法 接收用户输入的新水果名称
newFruit.name = enterString();
System.out.println("请输入新水果的单价: ");
//调用enterDouble方法 接收用户输入的新水果单价
newFruit.price = enterDouble();
System.out.println("请输入新水果的单位");
//调用enterString方法 接收用户输入的新水果单位
newFruit.unit = enterString();
//将新水果添加到集合中
list.add(newFruit);
}
//定义方法 完成用户键盘录入整数 参数 无 返回值 int 方法名enterNumber
public static int enterNumber(){
Scanner sc = new Scanner(System.in);
int enterNumber = sc.nextInt();
return enterNumber;
}
//定义方法 完成用户键盘录入字符串 参数 无 返回值 String 方法名enterString
public static String enterString(){
Scanner sc = new Scanner(System.in);
String enterString = sc.next();
return enterString;
}
//定义方法 完成用户键盘录入小数 参数 无 返回值 double 方法名enterDouble
public static double enterDouble(){
Scanner sc = new Scanner(System.in);
double enterDouble = sc.nextDouble();
return enterDouble;
}
}
|
|