学习时间:20210823
学习内容:
一、控制语句
1.if-else
代码示例:
。
public class Main {
//Math.random() 表示【0,1)
//Math.PI 表示Π
public static void main(String[] args) {
int a =(int)(Math.random()*6)+1;
int b =(int)(Math.random()*6)+1;
int c =(int)(Math.random()*6)+1;
if (a+b+c<10){
System.out.println("可以嘛小伙子"+(a+b+c));
}else if (a+b+c<20){
System.out.println("这脚气"+(a+b+c));
}else {
System.out.println("去去去"+(a+b+c));
}
}
}
if 后面不加
{
可能也有用的,但是暂时用不到,以后看到了直接搜一下。
2. switch
示例如下:
switch(expression){
case value :
//语句
break; //可选,否则就继续运行,知道break出现
case value :
//语句
break; //可选
default : //可选
//语句
}
有一点需要注意,以前没怎么在意的,就是这里的
expression
是有限制的,可以是整形(除了long),或者是字符(char)。
运行的基本逻辑是,和case对应上了,我才进入内部的语句;否则不进入,直到最后或default。
自己做一下:
public static void main(String[] args) {
int a = 5;
switch (a) {
case 1:
System.out.println("hello");
break;
case 5:
System.out.println("我就知道你回来");
break;
default:
System.out.println("ha?");
}
}
3.while
基本格式是:
while( 布尔表达式 ) { //循环内容}
选个例题做一下,理解一下:
1-120之间能够被5整除的数,打印出来。
int a = 1;
while (a <= 120) {
if (a % 5 == 0) {
System.out.println(a);
}
a++;
}
还有一个do while,就是while之前先都do一下,没什么东西。
4.for
基本格式是:
for(初始化; 布尔表达式; 更新) {
//代码语句
}
注意一下,里面用的是分号
选个例题做一下,理解一下:
使用for循环,打印出a-z 26个字母。
char a = 'a';
for (int i = 0; i < 26; i++) {
System.out.println((char) a + "\t");
a += 1;
}
其中的问题,一个是
+ "\t"
,中间的那个加号。
+号在一个是字符,另一个是数字时,是进行相加的。
5.嵌套循环
嗯……没有听,把课程作业做一下吧
99乘法表。
for (int i = 1; i <=9 ; i++) {
for (int j = 1; j <=i ; j++) {
System.out.print(i+"*"+j+"="+(j*i)+"\t");
}
System.out.print("\n");
}
6.break
退出循环,即退出最内侧的循环(for,while)
产生100以内的随机整数,直到88时终止循环。
int count =0;
while (true){
count++;
int i =(int)(Math.random()*101);
if (i==88){
break;
}
}
System.out.println("一共找了"+count+"次");
7.continue
退出当前次数循环,即退出最内侧的循环1次,顺滑出去(for,while)
把100-150内的不能用3整除的整数输出,每行输出5个。
int count = 1;
for (int i = 100; i <= 150; i++) {
if (i % 3 != 0) {
count++;
if (count % 5 == 1 && count != 1) {
System.out.print("\n");
}
System.out.print(i + "\t");
} else {
continue;
}
}
二、方法
1、定义与调用
举例
public static void main(){}
public static int max(){}
//修饰符(public + static)<和之前在solidity里面了解的一样,等后面再整理> + 返回值类型(int,long等) + 方法名 (定义一下方法名就行) + (参数 type 名字如:int num)
调用的话:
System.out.println("");//void 类型
int a = max();//普通带返回值的
2、通过值传递参数
记得在通过值传递参数时,参数值是传递过去的,但是参数本身没有改变。
public static void main(String[] args) {
int a = 0;
System.out.println(change(a));
System.out.println(a);
}
public static int change(int c) {
c = c + 1;
return c;
}
//结果:
1
0
3、方法重载
重载的方法必须拥有不同的参数列表。你不能仅仅依据修饰符或者返回类型的不同来重载方法。
即:!!!方法里面的参数必须要改变!!
public static void main(String[] args) {
int a = 0;
System.out.println(change(a));
System.out.println(a);
}
//原方法
public static int change(int c) {
c = c + 1;
return c;
}
//下面为正确
public static int change(double c) {
c = c + 1;
return (int) c;
}
//下面为错误,
public static double change(int c) {
c = c + 1;
return (double) c;
}
4、可变参数
public static void getMax(double... n) {
}
//此时n为多个参数
一个方法中只能指定一个可变参数,它必须是方法的最后一个参数。