本周新学会知识点
1、 得到一个多位数的各个位数(x)
int x1 = x % 10;
int x2 = (x / 10) % 10;
int x3 = (x / 100) % 10;
int x4 = (x / 1000) % 10;
int x5 = (x / 10000) % 10;
2、 变量互换(不用中间值)
x5 = x5 + x4;
x4 = x5 - x4;
x5 = x5 - x4;
3、 字符串的常用方法:
(int) str.length() 获取字符串长度
(String) str.trim(); 删除字符串前后空格
(boolean) str.equal(str1) 判断字符串是否相等
(String) str.substring(3,6) 从第4个之后开始到第6个取出子字符串
(int) Integer.parseInt(str) 把整数的字符串转换成int类型
4、 数学运算常用方法:
(int) Math.round(double) 四舍五入取整
(int) Math.ceil(double) 向上取整
5、 图形打印思路
外层循环控制行数
内层循环控制列数
\1.
for(int i = 0; i < 5; i++) {
for (int j = 0; j<i*2+1; j++) {
System.out.print("* ");
}
System.out.println();
}
2.
外层循环里面套两个内层循环,其中一个用输出空格
for (int i = 0; i < 5; i++) {
for (int j = 0; i+j<4; j++) {
System.out.print(" ");
}
for (int j = 0; j < i*2+1; j++) {
System.out.print("*");
}
System.out.println();
}
6、冒泡排序:
类似于冒泡: 1.相邻的两个比较,交换,把大的或小的数往后移动
2.最后一个数确定
3.循环上述操作
关键: 外层循环次数length-1,内层循环次数length-1-i
7、折半查找:Binary search:
思路: 待找数与中间数比较,确定待找数在左部份还是右部分
变换最大下标或最小下标
循环上述操作
如下加黑为细节:
int minIndex = 0;
int maxIndex = nums.length - 1;
int centerIndex = (minIndex + maxIndex) / 2;**//** **折半排序,通过最小下标,最大下标,中间下标变化查找**
while (true) { **//** **不确定循环的次数,用while**
if (nums[centerIndex] > 6) {
maxIndex = centerIndex - 1;
} else if (nums[centerIndex] < 6) {
minIndex = centerIndex + 1;
} else {
break; **//** **当中间下标的数等于要查找的数时,查找结束**
}
if (minIndex > maxIndex) {
centerIndex = -1;
break; **//** **当最小下标大于最大下标时查找结束**
}
centerIndex = (minIndex + maxIndex) / 2;//
}
if (centerIndex == -1) {
System.out.println("没找到!");
} else {
System.out.println("找到了,下标为:" + centerIndex);
}
8、 If …else if 无论条件是否矛盾,只执行一个:
题目:把所有0移到最后
public class MoveZero {
public static void main(String[] args) {
int nums[]= {0,1,0,3,12};
int temp=0;
for (int i = 0; i < nums.length; i++) {
if(nums[i]==0) {
temp++; //记录前面0的个数
}else if(temp!=0) {
nums[i-temp]=nums[i];
nums[i]=0;
}
}
for (int i = 0; i < nums.length; i++) {
System.out.print(nums[i]);
}
}
}
9、用数组解决一个圈循环问题
1、当i=n+1时,i=0,重新开始循环
2、循环条件全部为true,用break结束循环
题目:班级里所有人有个人围成一圈,顺序排号。从第一个人开始报数(从1到3报数),凡报到3的人退出圈子,问最后 留下的当选为班长,问班长是原来第几号的那位。
public class MonitorSelect {
public static void main(String[] args) {
int tatal_Number_People = 40;
int count = tatal_Number_People;
int temp = 0;
int nums[] = new int[tatal_Number_People];
for (int i = 0; i < tatal_Number_People; i++) {
nums[i] = 1;
}
for (int i = 0;; i++) {
if (i == tatal_Number_People) {
i = 0;
}
if (nums[i] == 1) {
temp++;
} else {
continue;
}
if (temp % 3 == 0) {
nums[i] = 0;
count--;
}
if (count == 1) {
break;
}
}
for (int i = 0; i < nums.length; i++) {
if (nums[i] == 1) {
System.out.println("班长是数组下标为"+i+"的位置的人");
}
}
}
}