1.传递基本数据类型的内存原理:
传递基本数据类型时,传递的是真实的数据,形参的改变,不影响实际参数的值
2.方法传递引用数据类型的内存原理:
传递引用数据类型时,传递的是地址值,形参的改变,影响实际参数的值
例题:
(1)需求:机票的价格按照旺季和淡季、经济舱和头等舱收费、输入机票原价、月份和头等舱或经济舱。已知,旺季(5~10月)头等舱9折优惠,经济舱8.5折,淡季(11~来年4月)头等舱7折,经济舱6.5折。
import java.util.Scanner;
//选中重复的代码简写成方法可以用快捷键ctrl + alt + M,自动抽取方法
public class Demo01 {
/*需求:机票的价格按照旺季和淡季、经济舱和头等舱收费,输入机票原价、月份和头等舱或经济舱。
已知,旺季(5~10月)头等舱9折优惠,经济舱8.5折,淡季(11~来年4月)头等舱7折,经济舱6.5折。*/
public static void main(String[] args){
//1.我需要做什么? 键盘录入输入机票原价、月份和头等舱或经济舱
Scanner sc = new Scanner(System.in);
System.out.println("请输入机票原价:");
int ticket = sc.nextInt();
System.out.println("请输入月份:");
int month = sc.nextInt();
System.out.println("请输入1.头等舱 2.经济舱");
int seat =sc.nextInt();
if(month >= 5 && month <=10){
//旺季
ticket = printPrice(ticket,seat,0.9,0.85);
}else if(month >= 11 && month <= 12 || month >= 1 && month <= 4){
//淡季
ticket = printPrice(ticket,seat,0.7,0.65);
}else{
System.out.println("输入的月份不合法");
}
System.out.println("机票折扣后的价格为:" + ticket);
}
//2.干这件事,需要用什么解决? 判断月份是否是旺季和淡季,继续判断机票是头等舱还是经济舱、头等舱的折扣、经济舱的折扣
public static int printPrice(int ticket, int seat, double n1, double n2){
if(seat == 1){
ticket = (int)(ticket * n1);
}else if(seat == 2){
ticket =(int)(ticket * n2);
}else{
System.out.println("没有该舱位");
}
//3.是否需要返回结果? 需要
return ticket;
}
}
(2)需求:判断101~200之间有多少个质数,并打印所有质数。
public class Demo02 {
public static void main(String[] args){
//判断101~200之间有多少个质数,并打印所有质数。
//1.我需要做什么? 循环得到 101~200之间的数
//2.完成这件事,我需要怎么实现? 判断是否是质数
int count = 0;
//外循环 遍历101~200这个范围,依次得到这个范围的每一个数
for (int i = 100; i <= 200; i++) {
boolean flag = true;
for(int j = 2; j < i;j++){
if(i % j == 0){
flag = false;
//跳出单层循环,内循环
break;
}
}
if(flag){
System.out.println("当前数" + i + "是质数");
count++;
}
}
System.out.println("一共有" + count + "个质数");
}
}
运行结果:
(3)需求:定义方法实现随机产生一个5位的验证码
验证码格式:长度为5,前四位是大写字母或者小写字母,最后一位是数字。
import java.util.Random;
public class Demo03 {
public static void main(String[] args){
//1.分析:将大写字母和小写字母存到数组中
char[] st = new char[52]; //26 + 26
Random r = new Random();
for (int i = 0; i < 52; i++) {
if(i <= 25){
st[i] = (char)(97 + i);
}else{
st[i] = (char)(65 + i -26);
}
}
String result = ""; //长度为0,什么都没有的字符串
for (int i = 0; i < 4; i++) {
int index = r.nextInt(st.length);
result = result + st[index];
}
int number = r.nextInt(10);
result = result + number;
System.out.println("随机生成的五位验证码为:" + result);
}
}
运行结果:
(4)需求:把一个数组中的元素复制到另一个新的数组中
public class Demo04 {
public static void main(String[] args){
int[] arr = {1,2,3,4,5,6,7,8,9,10};
int[] newarr = new int[arr.length];
for (int i = 0; i < arr.length; i++) {
newarr[i] = arr[i];
}
System.out.println("新的数组元素为:");
for (int i = 0; i < newarr.length; i++) {
System.out.print(newarr[i] + " ");
}
}
}
运行结果: