056_带标签的break和continue 057_方法的定义_形参_实参_返回值_语句块 058_方法的重载overload 059_递归算法详解_递归和迭代效率测试

 

056_带标签的break和continue(替代被取消的goto语句)

 

 

 

加个计数器:

 

 


/**
* 带标签的Break和Continue
*
* @author
*
*/
public class TestLabelContinue {
public static void main(String[] args) {
// 打印101-150之间所有的质数
int count = 0;// 定义计数器

outer: for (int i = 2; i < 1000; i++) {
for (int j = 2; j < i / 2; j++) {//测试2到被除数的一半就行了,效率
if (i % j == 0) {

continue outer;
}
}
System.out.print(i + " ");
count++;// 没输出一个数,计数器加1
if (count % 5 == 0) {
System.out.println();
count = 0;
}
}
}
}

 

057_方法的定义_形参_实参_返回值_语句块

 

 

 


/**
* 测试方法的基本使用
* @author
*
*/
public class TestMethod {
public static void main(String[] args) {
//通过对象调用普通方法
TestMethod tm = new TestMethod();
tm.printSxt();
tm.printSxt();

int c = tm.add(30, 40, 50)+1000;//实际参数
System.out.println(c);
}

void printSxt(){
System.out.println("北京学堂...");
System.out.println("上海学堂...");
System.out.println("广州学堂...");
}

int add(int a, int b, int c){//形式参数
int sum = a+b+c;
System.out.println(sum);
return sum; //return 两个作用:1.结束方法的运行。2.返回值
}

}

 

058_方法的重载overload

 

 

 

 

有static的方法可以直接调用,不用new

可以重载的情况:

 

 不能重载的情况:

 059_递归算法详解_递归和迭代效率测试

 

 


/**
* 测试递归
* @author
*
*/
public class TestRecursion01 {
public static void main(String[] args) {
a();
}

static int count = 0;
static void a(){
System.out.println("a");
count++;
if(count<10){ //只打印十次限制递归次数
a();
}else{
return; //return的作用:返回值、结束方法运行
}

}

static void b(){
System.out.println("b");
}


}

 

 

 递归消耗大量资源,尽量用普通循环替代(爬虫除外)

posted @ 2020-09-05 18:15  小白冲  阅读(218)  评论(0编辑  收藏  举报