方法:实现一定的功能的代码的集合
方法名字:首字母小写,后面单词的首字母大写
java中方法的定义:
return的作用:方法的返回,将计算结果返回或者结束方法
修饰符 返回值类型 方法名(参数列表){
方法的功能主体
循环、判断、变量、比较、运算
Return 返回值;
}
JAVA方法实例
方法调用内存图
方法的定义与调用问题实例
方法的重载问题:
在同一个类中,允许出现同名的方法,只要方法的参数列表不同即可,这就是方法的重载
方法参数的不同类型
1、方法参数为基本类型:不返回值
2、方法参数为引用数据类型:传递的是内存的地址,方法中数据改变会引起调用结果的改变
重写随机点名器
根据不同功能封装成不同的方法
import java.util.Scanner; public class Shopp{ public static void main(String[] args){ //定义数组 //品牌 String,尺寸double,价格double,库存 int。 String[] brands={"MacBookAir","ThinkpadT450","ASUS_FL5800"}; double[] sizes={13.3,14,15.6}; double[] prices={6988.88,5999.99,4999.5}; int[] counts={5,10,18}; while(true){ int choose=ChooseFunction(); switch(choose){ case 1: //调用printStore,打印商品信息 PrintStore(brands,sizes,prices,counts); break; case 2: //修改商品信息 UpdateStore(brands,counts); break; case 3: return; default : System.out.println("---------------------------------"); System.out.println("您输入的数据有误,请重新输入:"); break; } } //ChooseFunction(); //调用PrintStore,打印商品信息 //PrintStore(brands,sizes,prices,counts); } public static void PrintStore(String[] brands,double[] sizes,double[] prices,int[] counts){ //定义累加和 int totalCount=0; double totalPrice=0.0; //输出表头文字 System.out.println("------------------商城库存清单-------------------------------"); System.out.println("品牌型号 尺寸 价格 库存数"); //遍历输出数组元素 for(int i=0;i<brands.length;i++){ System.out.println(brands[i]+" "+sizes[i]+" "+prices[i]+" "+counts[i]); totalCount+=counts[i]; totalPrice+=prices[i]*counts[i]; } //输出总金额 System.out.println("总库存数:"+totalCount); System.out.println("库存商品总金额:"+totalPrice); } public static int ChooseFunction(){ System.out.println("---------------库存管理------------------"); System.out.println("1、查看库存清单"); System.out.println("2、修改商品库存数量"); System.out.println("3、退出"); System.out.println("请输入需要执行的程序编号:"); //接收键盘的输入 Scanner sc=new Scanner(System.in); int choose=sc.nextInt(); return choose; } public static void UpdateStore(String[] brands,int[] counts){ //接收键盘输入 Scanner sc=new Scanner(System.in); //遍历数组 for(int i=0;i<counts.length;i++){ System.out.println("请修改"+brands[i]+"的库存数量:"); //键盘输入,录入库存数组 int newcount=sc.nextInt(); counts[i]=newcount; } } }