一阶段:JavaSE学习05拓展
看不懂或者不想看的可以跳往下一篇,这个只是让你知识面更宽更广
返回值类型拓展
/**
* @author 你的大龙猫啊
*/
/*
返回值类型拓展
*/
public class Expand08_Return {
public static void main(String[] args) {
System.out.println(getMax(10, 20));
}
private static int getMax(int a,int b){
if(a>b){
return a;
}
else{
return b;
}
/*else if(a<b)( 思考:为什么使用if....else if会报错 而使用 if...else不会报错
return b; 原因:if和 else if搭配:是不是有可能if和else if都不执行 如果不执行,那么就说明这个方法缺少返回值
) if和else的搭配:不管将来的条件是什么,必然会执行一个返回语句
也许有人想问,如果else if条件是a<=b 结果会怎样? ---计算机才不懂你这个,一样报错
*/
}
}
数据交换拓展
思考:如何才能不借用第三个变量去交换两个数或者数组集合?(面试曾经出现过)
/**
* @author 你的大龙猫啊
*/
/*
数据交换扩展
^:位异或
如何区别逻辑异或和位异或? 逻辑异或两边连接的是表达式,只有true和false
^运算符的特点:一个数,被另一个数异或两次,该数本身不变
*/
//需求:已知两个整数变量a=10,b=20,使用程序时间这两个变量的数据交换 最终输出a=20,b=10; 不允许使用三方变量
public class Expand09_DataChange {
public static void main(String[] args) {
int a = 10;
int b = 20;
//这里举的是一个最简单的例子,交换的可以是数组和集合等...
a = a ^ b; //a = 10^20;
b = a ^ b; //b = 10^20^20; ===> b=10;
a = a ^ b; //a = 10^20^10; ===> a=20;
System.out.println("a:" + a);
System.out.println("b:" + b);
}
}
练习
/**
* @author 你的大龙猫啊
* @company www.com.hui
*/
/*
需求:已知一个数组arr={19,28,37,45,50};用程序实现吧数组中的元素值交换,
交换后的数组arr={50,46,37,28,19};并在控制台输出交换的数组元素。
格式为:[19, 28, 37, 45, 50] ---使用位异或
*/
public class Expand09_DataChange02 {
public static void main(String[] args) {
int[] arr = {19, 28, 37, 45, 50};
int start = 0;
int end = arr.length - 1;
//使用for循环
// for (int start = 0, end = arr.length - 1; start < end; start++, end--)
/* for (; start < end; start++, end--) {
int temp = arr[start]; //使用的是第三方变量接收
arr[start] = arr[end];
arr[end] = temp;
}*/
//使用while循环 for与while通用(for能做的事while也能做)
while(start<end){
/*int temp = arr[start]; //使用的是第三方变量接收
arr[start] = arr[end];
arr[end] = temp;*/
//使用位异或
arr[start] = arr[start]^arr[end]; //arr[start] = arr[start]^arr[end]
arr[end] = arr[start] ^arr[end]; //arr[end] = arr[start]^arr[end]^arr[end] ====>arr[start]
arr[start] =arr[start]^arr[end]; //arr[start]= arr[start]^arr[end]^arr[start] ====>arr[end]
start++;
end--;
}
//无格式遍历,做测试
/*for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}*/
System.out.print("[");
for (int i = 0; i < arr.length; i++) {
if(i==arr.length-1){
System.out.print(arr[i]);
}else{
System.out.print(arr[i]+",");
}
}
System.out.println("]");
}
}
本文深入探讨了JavaSE中返回值类型的拓展应用,通过实例解析了if...else与if...elseif的差异,并介绍了如何利用位异或进行数据交换,包括变量和数组的交换技巧。
8万+





