Java任务:方法重载之查找商品
来自CloudWiki
任务描述:查找商品
用户有时需要根据不同的条件来查询商品,你的任务是编写两个版本的showInfo()方法,分别用于查询所有商品和指定名称的商品。
任务实现
数据库查询的细节会在后面的任务详细讲解。这里使用测试数据演示方法重载功能。
package entity; public class Store { private Noodles [] nset; private int num ; public Store() { num = 3; nset = new Noodles[num]; nset[0]= new Noodles("山西刀削面",105.0f,30); nset[1]= new Noodles("兰州牛肉面",15.0f,20); nset[2]= new Noodles("北京炸酱面",12.0f,30); } public int getNum() { return this.num; } public void getSet() { for(int i=0;i<nset.length;i++) { System.out.println(nset[i].toString()); } } public String showInfo() { String total=""; for(int i=0;i<nset.length;i++) { total +=nset[i].toString()+"\n"; } return total; } public String showInfo(String name) { String s="暂无商品信息"; for(int i=0;i<this.nset.length;i++){ if (this.nset[i].getName().equals(name)) { s = this.nset[i].toString(); } } return s; } public String toString() { String total=""; for(int i=0;i<nset.length;i++) { total +=nset[i].toString()+"\n"; } return total; } public static void main(String[] args) { // TODO Auto-generated method stub Store s = new Store(); System.out.println("仓库的商品总数为:"+s.getNum()); System.out.println("以下为商品详情信息:"); System.out.println(s.showInfo()); System.out.println("查找山西刀削面:"); System.out.println(s.showInfo("山西刀削面")); } }
返回 Java程序设计